p5.js中的constrain()函數用於將數字限製在給定的最小和最大限製之間。
用法:
constrain( n, low, high )
參數:此函數接受上述和以下所述的三個參數:
- n:它是一個數字,表示必須約束的值。
- low:它是一個數字,表示該數字所受的最小限製。
- high:它是一個數字,表示該數字所受的最大限製。
返回值:它返回一個帶有約束值的數字。
以下示例說明了p5.js中的constrain()函數:
範例1:
function setup() {
createCanvas(650, 200);
textSize(20);
inputElemA = createInput(10);
inputElemA.position(30, 40);
inputElemB = createInput(100);
inputElemB.position(30, 60);
sliderElem = createSlider(-100, 100, 50, 1);
sliderElem.position(30, 120);
}
function draw() {
clear();
text("Enter two values between which the "
+ "number would be constrained", 20, 20);
text("Move the slider to observe the effects"
+ " of the constrain() function", 20, 100);
// Convert the string value to a number value
inputValA = Number(inputElemA.value());
inputValB = Number(inputElemB.value());
sliderVal = sliderElem.value();
text("The slider value is:" + sliderVal, 20, 160);
// Display the constrained value
text("The constrained value is:"
+ constrain(sliderVal, inputValA,
inputValB), 20, 180);
}
輸出:
範例2:
function setup() {
createCanvas(600, 350);
textSize(20);
}
function draw() {
clear();
text("Move the pointer to see the effect "
+ "of constrain() in the square", 20, 30);
text("White circle represents unconstrained"
+ " mouse", 20, 50);
text("Red circle represents mouse constrained"
+ " to box dimensions", 20, 70);
noFill();
square(100, 100, 200);
circle(mouseX, mouseY, 40);
// Constrain the mouse x and y position
constrainedMouseX = constrain(mouseX, 100, 300);
constrainedMouseY = constrain(mouseY, 100, 300);
fill('red');
circle(constrainedMouseX, constrainedMouseY, 20);
}
輸出:
在線編輯: https://editor.p5js.org/
環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
參考: https://p5js.org/reference/#/p5/constrain
相關用法
- p5.js cos()用法及代碼示例
- p5.js sin()用法及代碼示例
- PHP each()用法及代碼示例
- PHP each()用法及代碼示例
- p5.js tan()用法及代碼示例
- p5.js nfc()用法及代碼示例
- PHP Ds\Set contains()用法及代碼示例
- p5.js log()用法及代碼示例
- p5.js max()用法及代碼示例
- d3.js d3.min()用法及代碼示例
- p5.js nf()用法及代碼示例
- p5.js second()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js | constrain() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。