Skip to content
Related Articles

Related Articles

Improve Article

p5.js map() Function

  • Last Updated : 17 Feb, 2021

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :