Understanding the map() Function in p5.js

The map() function in p5.js re-scales a number from one range to another. This is especially useful for converting input values—like mouse coordinates or sensor data—into visual properties such as color, size, or position.

Function Signature

map(value, low1, high1, low2, high2, [clamp])
  • value: The incoming value to be mapped.
  • low1, high1: The lower and upper bounds of the original range.
  • low2, high2: The lower and upper bounds of the target range.
  • clamp (optional): If true, the result will be constrained with in [low2, high2]. Default is false.

Basic Example

Suppose you want to convert a value from [0, 100] to [0, 10]:

let output = map(40, 0, 100, 0, 10); // returns 4

If the input exceeds the original range and clamping is disabled, the output can go beyond the target range:

let unclamped = map(600, 0, 100, 0, 10);     // returns 60
let clamped    = map(600, 0, 100, 0, 10, true); // returns 10

Interactive Backgorund Using Mouse Position

This sketch maps the horizontal mouse position to a grayscale background:

function setup() {
  createCanvas(300, 200);
}

function draw() {
  let brightness = map(mouseX, 0, width, 0, 255, true);
  background(brightness);
}

Note: width and height refer to the canvas dimensions, which are more reliable than windowWidth/windowHeight when the canvas doesn’t fill the entire window.

HSB Color Control with 2D Mapping

Map both X and Y mouse coordinates to control hue and saturation:

function setup() {
  createCanvas(320, 200);
  colorMode(HSB, 360, 100, 100); // Hue: 0–360, Saturation/Brightness: 0–100
}

function draw() {
  let hueVal = map(mouseX, 0, width, 0, 360, true);
  let satVal = map(mouseY, 0, height, 0, 100, true);
  background(hueVal, satVal, 100);
}

This demonstrates how map() enables intuitive interaction by linking physical input (mouse) to abstract visual parameters.

The map() function is also valuable in animations, data visualization, and 3D graphics—anywhere proportional scaling between domains is needed.

Tags: p5.js Map creative coding interactive graphics javascript

Posted on Thu, 30 Jul 2026 16:42:04 +0000 by matty84