Creative Coding · Session c02
Colour
How computers think about colour — and how to use it.
In the last session you mixed colours using three numbers: Red, Green, Blue (RGB). Today you'll discover a second colour system — HSB — which often feels more natural for artists. And you'll make your first interactive sketch: one that reacts to your mouse.
RGB vs HSB
RGB: Mix three channels — Red (0–255), Green (0–255), Blue (0–255). Good for computer screens, tricky for humans to predict.
HSB: Describe colour as: Hue (the colour: 0–360°, like a colour wheel), Saturation (0 = grey, 100 = vivid), Brightness (0 = black, 100 = bright). Much more intuitive!
In p5.js: colorMode(HSB, 360, 100, 100) switches the mode. Then fill(0, 100, 100) = pure red, fill(120, 100, 100) = pure green, fill(240, 100, 100) = pure blue.
Live sketch — Mouse Colour Mixer
Move your mouse (or finger) across the canvas. The background hue follows your horizontal position. Three circles blend together with transparency — you can see additive colour mixing.
function setup() {
createCanvas(420, 260);
colorMode(HSB, 360, 100, 100);
}
function draw() {
let hue = map(mouseX, 0, width, 0, 360);
background(hue, 30, 95);
noStroke();
fill(0, 100, 100, 0.5);
ellipse(150, 140, 150);
fill(120, 100, 100, 0.5);
ellipse(210, 100, 150);
fill(240, 100, 100, 0.5);
ellipse(270, 140, 150);
}
The map() function
map(value, fromLow, fromHigh, toLow, toHigh) is one of the most useful tools in creative coding. It re-scales a number from one range into another:
Example: map(mouseX, 0, width, 0, 360) — if the canvas is 420px wide and the mouse is at x=210 (the middle), the result is 180 (halfway around the colour wheel).
Challenges
- Change the three primary hues to different values. What does
fill(60, 100, 100) give you? What about fill(300, 100, 100)?
- Make the circles change size with
mouseY. Map mouseY (0 → height) to a diameter (50 → 250).
- Change saturation based on mouseY:
let sat = map(mouseY, 0, height, 100, 0). What happens as you move down?
- Try
colorMode(RGB) and set the same three circles to red, green, blue using fill(255,0,0,127) style (alpha 0–255 in RGB mode).
- Open challenge: Build a "sunset" — three colours that slowly shift from orange to deep purple as the mouse moves left to right.
Next session → c03: Variables & Motion
You'll learn how variables store numbers that change over time, and how to use sin() to create smooth, natural-looking movement — a "breathing" jellyfish that pulses on screen.