Unit 2 Response & Draw
How can control flow allow for user interactions?

1.5 Map Function

How can the map function help me control a range of values?


Overview

This learning activity introduces the map function, and applies it to changing a sketch`s background color to grayscale, RGB, and HSB color ranges.

Suggested Duration

30 minutes

Objectives

Students will be able to:

  • Use the map function to control color.
  • Utilize pmouseX and pmouseY to create something that draws.

Vocabulary

map() A built-in p5.js function that re-maps a number from one range to another.

Resources

  • Video tutorial: 2.4: The map() Function | Code
  • Learning Processing: Chapter 13, Section 13.5
  • Getting Started With p5.js: Chapter 5 (Section: Map)

Vary the background with mouseX

Suppose we would like to have the background of our sketch go from black to white as we move across the screen. We might do it this way:

You might have noticed, however, that the background is fully white before we reach the half of the screen. This is the mouse position ranges from 0 (when we are on the left edge of the canvas), to 600 (when we are on the right edge), while the background gray ranges from 0 to 255. Our maximum mouseX position (600) is not the same as our maximum value for color (255 for white). So when the mouse reaches pixel 255, the screen is white.

This is a situation that happens over and over again as we create responsive systems: we have an input range (in this case 0 to 600), and we need to map it to a certain output range (in this case 0 to 255). It is not hard to solve this problem using simple math (a rule of three), but it is so recurrent that there is a p5 function to solve it quickly, the map function. It takes the variable to be mapped (in this case mouseX), the range that we know it will be in (0 to width), and the output range we want (0 to 255).

In this example the mouseX controls the amount of red, and the mouseY the amount of green.

And here we are using HSB mode, and varying the hue with the mouseX. Because hue is represented as an angle on a circle, from red (0), through all other hues, and back to red (360), our output range is now (0, 360).