p5.js |约束()函数


p5.js |约束()函数

p5.js 中的constrain()函数用于将数字限制在给定的最小和最大限制之间。

句法:

constrain( n, low, high )

参数:此函数接受三个参数,如上所述,如下所述:

  • n:它是一个数字,表示必须约束的值。
  • 低:这是一个数字,表示限制该数字的最小限制。
  • 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


Made with ❤️ in Chengdu. Copyright reserved 2019-2023.

蜀ICP备20006366号-1