Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptp5.js map() Function

p5.js map() Function

The map() function in p5.js is used to normalize a number having range from min1 to max1 in a range of min2 to max2.

Normalization is very helpful in p5.js if you are scaling your elements. Because as we know normalization takes care of all the proportions in scaling so, we get a completely balanced scaling.

Not just scaling but in any transformation operations normalization is very helpful.

Syntax:

map(value, start1, stop1, start2, stop2, [withinBounds])

Parameters: This function accepts six parameters as mentioned above and described below:

  • value: The value you want to normalize.
  • min1: Minimum value of the value’s current range.
  • max1: Maximum value of the value’s current range.
  • min2: Minimum value of the value’s target range.
  • max2: Maximum value of the value’s target range.
  • withinBounds (optional): This restricts the normalized value of value in range of [min2, max2].

Example 1: WithinBounds is false by default.

Javascript




function setup() {
    noLoop();
}
  
function draw() {
  
    background(220);
  
    // Assume value has range [0, 100]
    let value = 50;
  
    // We want to convert value 
    // in range of [0, 50]
    let newValue = map(value, 0, 100, 0, 50);
  
    console.log(newValue);
}


Output:

25

Example 2: Notice how withinBounds constraints range of value

Javascript




function setup() {
    noLoop();
}
  
function draw() {
  
    background(204);
  
    // Value has a range[0, 100]
    let value = 150;
  
    // We are mapping it in range of [0, 50]
    let newValue1 = map(value, 0, 100, 0, 50);
  
    console.log(newValue1);
  
    // Notice the last parameter is true
    // we are mapping it in range of [0, 50]
    let newValue2 = map(value, 0, 100, 0, 50, true);
  
    console.log(newValue2);
}


Output:

75
50

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments