當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js lerp()用法及代碼示例

lerp()函數用於查找兩個數字之間的數字。 amt參數可用於指定要在兩個值之間插值的量。接近0.1的值表示最終值接近於第一個值,而接近0.9的值表示該值接近第二個值。如果該值小於或大於這些值,則將基於兩個數字的比率來計算最終值。

通過查找一條線中的所有中間點,可將其用於繪製虛線或沿路徑創建運動。

用法:



lerp( start, stop, amt )

參數:此函數接受上述和以下所述的三個參數:

  • start:它是一個數字,表示兩個數字中的第一個值。
  • stop:它是一個數字,表示兩個數字中的第二個值。
  • amt:它是一個數字,表示在兩個數字之間插入一個數字的數量。

返回值:它返回一個帶有值的數字。

以下示例說明了p5.js中的lerp()函數:

範例1:

function setup() { 
  createCanvas(600, 200); 
  textSize(20); 
   
  inputElemA = createInput(10); 
  inputElemA.position(30, 40); 
   
  inputElemB = createInput(100); 
  inputElemB.position(30, 60); 
   
  sliderElem = createSlider(0, 1, 0.5, 0.1); 
  sliderElem.position(30, 120); 
} 
   
function draw() { 
  clear(); 
  text("Enter two values between which new "
        + "number would be lerped", 20, 20); 
  text("Move the slider to observe the amount"
        + " of lerping", 20, 100); 
   
  // Convert the string value to a number 
  // value for lerping 
  inputValA = Number(inputElemA.value()); 
  inputValB = Number(inputElemB.value()); 
  sliderVal = sliderElem.value(); 
   
  text("The amount of lerping is:"
        + sliderVal, 20, 160); 
          
  text("The lerped value is:"
        + lerp(inputValA, inputValB,  
        sliderVal), 20, 180); 
}

輸出:
lerp-slider

範例2:

function setup() { 
  createCanvas(600, 300); 
  textSize(20); 
  
  sliderElem = createSlider(0, 1, 0.5, 0.1); 
  sliderElem.position(30, 180); 
  
  circleApos = 50; 
  circleBpos = 500; 
} 
  
function draw() { 
  clear(); 
  text("Move the slider to observe the x position "
          + "of the middle circle", 20, 160); 
  
  circle(circleApos, 50, 80); 
  circle(circleBpos, 50, 80); 
  
  sliderVal = sliderElem.value(); 
  lerpedVal = lerp(circleApos, circleBpos, sliderVal); 
  
  // Draw the circle at the lerped x coordinate 
  circle(lerpedVal, 50, 80); 
  
  text("The amount of lerping is:" + sliderVal, 20, 220); 
}

輸出:
circle-lerp

在線編輯: https://editor.p5js.org/

環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

參考: https://p5js.org/reference/#/p5/lerp




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js | lerp() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。