Open In App

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:

Example 1: WithinBounds is false by default.




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




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

Article Tags :