Lesson 23 · Creative Coding

Drawing with p5.js

$y = mx + b$ in code — then art, animation, and colour.

p5.js is a JavaScript library built for creative coding — drawing, animation, and digital art in the browser. It was created by artists and designers, and it is used in art schools, museums, and studios around the world. The code runs right here on this page. No install needed.

You will start with the maths you already know: plotting $y = mx + b$. Then you will use the same tools to draw patterns, react to your finger, and make a spinning flower. After that — it's yours to explore.

Part 1 · The Maths Sketch — $y = mx + b$

Drag the sliders. The sketch redraws every frame — 60 times per second.

Live sketch
The p5.js idea — setup and draw
Every p5.js sketch has two functions:
 • setup() runs once when the page loads — create the canvas here.
 • draw() runs 60 times per second — draw the picture here.
This loop is why things feel alive: each frame, the code re-reads the sliders and repaints everything.
// Coordinate conversion: 1 maths unit = 30 pixels; y-axis is flipped function mathX(mx) { return 100 + mx * 30; } // right 30px per unit function mathY(my) { return 220 - my * 30; } // up 30px (y flipped!) function setup() { createCanvas(420, 280); // a 420×280 pixel drawing area } function draw() { background(245); // repaint the canvas each frame (light grey) // read the slider values let m = parseFloat(document.getElementById('slope').value); let b = parseFloat(document.getElementById('intercept').value); // draw grid, axes, tick labels (see full code in page source) // the line: pick two far-apart points on y = mx + b stroke(58, 134, 255); // blue strokeWeight(2.5); line(mathX(-1), mathY(m*-1+b), mathX(11), mathY(m*11 +b)); // blue dot at the y-intercept (where x = 0) fill(58, 134, 255); noStroke(); circle(mathX(0), mathY(b), 10); }
createCanvas(420, 280): makes a 420-pixel-wide, 280-pixel-tall drawing area.
background(245): fills the canvas with colour 245 (light grey). Called at the start of every frame to erase the previous drawing.
stroke / fill: stroke() sets the outline colour; fill() sets the inside colour. Three numbers = red, green, blue (each 0–255).
line(x1, y1, x2, y2): draws a straight line between two points in SVG-pixel coordinates.
circle(cx, cy, diameter): draws a circle at centre (cx, cy) with the given diameter.
Maths ↔ Code
m is the slope from Lessons 16–17. b is the y-intercept from Lesson 22.
mathX() and mathY() are the same coordinate conversion from the previous lesson — just written as a function instead of a formula. Programming is the same algebra, given a canvas.
Part 2 · Creative Starters

Three short sketches that show what else p5.js can do. Move your mouse over each one (or use your finger on the iPad).

Starter A Colour Grid — loops + colour from position
function draw() { noStroke(); for (let x = 0; x < width; x += 40) { // step across in 40px jumps for (let y = 0; y < height; y += 40) { // step down in 40px jumps let d = dist(x, y, mouseX, mouseY); // distance from your mouse fill(x * 0.6, y * 1.3, d); // R from x, G from y, B from distance square(x, y, 39); } } }
for loop: repeats the code inside the braces — once for each position on the grid. Two nested loops cover rows and columns.
dist(x, y, mouseX, mouseY): calculates the distance between the grid cell and the mouse. As you move the mouse, d changes — and so does the blue channel of every square.
fill(R, G, B): sets the colour using red (0–255), green (0–255), blue (0–255). Here, the position and mouse distance become colour values directly.
Starter B Follow the Mouse — interaction + trail
function setup() { createCanvas(420, 200); background(245, 245, 240); // paint the background once at the start } function draw() { // semi-transparent background → previous frames fade slowly (trail effect) background(245, 245, 240, 20); // 4th number = opacity (0–255) noStroke(); fill(255, 100, 180); // pink: R=255 G=100 B=180 circle(mouseX, mouseY, 60); // circle follows your finger }
background(..., 20): the fourth number is opacity. At 20/255 ≈ 8% opaque, the background only partially covers the previous frame — so older circles fade slowly instead of vanishing immediately. This creates the trail.
mouseX, mouseY: p5.js automatically tracks the mouse (or finger on a touchscreen). These two variables update 60 times per second.
Starter C Spinning Flower — angles + rotation
function setup() { createCanvas(420, 220); } function draw() { background(20); // near-black background translate(width/2, height/2); // move the origin to the canvas centre rotate(frameCount * 0.01); // spin a little each frame for (let i = 0; i < 12; i++) { // 12 petals push(); // save the current rotation state rotate(i * TWO_PI / 12); // rotate by 360°/12 = 30° per petal fill(i * 20, 100, 200); noStroke(); // colour shifts with each petal ellipse(60, 0, 20, 60); // draw one petal 60px from centre pop(); // restore rotation state } }
translate(width/2, height/2): moves the drawing origin to the centre of the canvas. Everything after this is drawn relative to the centre.
frameCount: counts how many times draw() has run since the sketch started. Multiplying by 0.01 gives a smooth, slow rotation.
TWO_PI / 12: TWO_PI = 2π ≈ 6.28 radians = 360°. Dividing by 12 gives 30° per petal. Connecting to Lesson 13: the 12 petals sum to 360°.
push() / pop(): save and restore the rotation state. Without them, each petal's rotation would add to the previous one and everything would spin out of control.
Challenges
  1. Challenge 1 · Math sketch
    Drag the slope slider to exactly 0. What equation does the label show? What does the line look like — and why does the blue dot not move when you change the slope?
    When m = 0, y = 0x + b = b. The y-intercept is the whole story — the slope has vanished.
  2. Challenge 2 · Starter A
    In Starter A, the fill() uses x * 0.6, y * 1.3, and d. Move your mouse slowly from the top-left to the bottom-right corner. Which colour channel (red, green, blue) changes with each direction of movement? Why?
    x controls red, y controls green, distance d controls blue. Moving right increases x → more red. Moving down increases y → more green.
  3. Challenge 3 · Starter B — try at editor.p5js.org
    Copy the Starter B code into editor.p5js.org. Change background(245, 245, 240, 20) to background(245, 245, 240, 200). Run it. What happens to the trail? Then try 2005. Explain in one sentence why changing this number changes the trail length.
    Higher opacity = the background paints over old frames more aggressively = shorter trail. Lower opacity = old frames persist longer = longer, ghostly trail.
  4. Challenge 4 · Starter C — angles
    In Starter C, change 12 (the number of petals) to 8 everywhere it appears in the code. What angle separates each petal now? (Use: $360° \div 8$.) Try 6, then 24. What shape emerges with very many petals?
    8 petals → 45° each. 24 petals → 15° each. Many petals → the outline approaches a circle.
  5. Challenge 5 · Open — make something your own
    Go to editor.p5js.org and make a sketch that is yours. It should:
     • Use at least one for loop
     • Use at least two different colours
     • Have some connection to something you love — a horse, a place you've visited, a pattern from nature

    There is no wrong answer. Save it and show someone.
Where to go from here
editor.p5js.org
Free online editor — works on iPad. Write, run, and save your own p5.js sketches without installing anything. Press the ▶ button to run.
openprocessing.org
Gallery of thousands of creative p5.js sketches by artists and students around the world. Click any sketch → "Remix" to open its code and change it.
The Coding Train — YouTube
Dan Shiffman teaches creative coding with p5.js in an enthusiastic, accessible style. Start with "Code! Programming for Beginners" or the p5.js playlist.
You have completed all 23 lessons 🎉 From solving for $x$ to spinning flowers — that is the full arc from Grade 7 equations to creative coding. The next mathematical chapter is systems of equations: when two lines cross, both equations are true at once. You already saw this in Challenge 1 of Lesson 22 — where two savings accounts reached the same total after the same number of weeks.
Note for parent / tutor
The three sketches on this page run entirely in the browser — no install, works on iPad. The p5.js library is bundled locally (/assets/p5.min.js), so it works offline on the local Wi-Fi server.

For experimenting: editor.p5js.org is the best next step — free, iPad-compatible, sketches are saved to the browser. Mia can keep a "sketch journal" there.

The Coding Train (YouTube) is the recommended follow-on resource. Dan Shiffman's "10 Minute p5.js" videos are a good starting point for independent exploration. The library is the same one used in creative coding courses at NYU, MIT Media Lab, and design schools worldwide.
← All lessons
Focus 25:00

Ask your tutor