home/ atoms/ p5js-map-function

p5.js map() rescales a value from one numeric range into another

map(value, start1, stop1, start2, stop2) takes a number that lives in [start1, stop1] and returns the equivalent position in [start2, stop2]. For example, map(mouseX, 0, width, 0, 255) converts a horizontal mouse position (0 to canvas width) into a colour component (0 to 255). Without map(), a beginner must write the linear-interpolation formula by hand; with it the conversion is one readable call. This makes it the go-to tool for interaction- and audio-reactive sketches: mouse position, audio amplitude, or sensor readings can all be rescaled to any output-parameter range. A common mistake is passing the ranges in the wrong order, which reverses the mapping.

Examples

function draw() {
  let r = map(mouseX, 0, width, 0, 255);
  background(r, 0, 150); // shifts blue→red as the mouse moves right
}

Assessment

Write a sketch that maps mouseY to a circle’s size (10 to 100) and mouseX to its red channel (0 to 255). Predict what happens if you swap start1/stop1 with start2/stop2.

“This video covers the map() function in p5.js -- how to take a value from a given range and map it to a new range.”