← Teacher guides

Teacher guide: Drawing and animation with p5.js

Draw and animate with JavaScript and p5.js: shapes, movement, decisions, lists, objects and functions, ending in a small game you build yourself.

Open the student course · How the ideas build

Each lesson works two ways. Students can work through the online tutorial at their own pace (it checks their answers and saves their progress in their browser), or you can teach it to the whole class from the slides, then send students into the tutorial for the Modify and Make steps.

Every lesson guide has plain-language notes, the answers to every check, a solution for every task, and slides and a worksheet for Waypoints Prepare. These guide pages are not linked from student pages, but they are not secret either: keep printed Teacher editions for answers you do not want students to find.

Strategies for getting unstuck: Say what it should do, Test a small piece, Read the error, Trace it. A student who is stuck can try one before asking for a hint. The optional course How you learn best introduces them, and a few lesson decks have a short teach, show or nudge slide for one. (Each lesson page links to the cards from its first hint.)

Whole-course cheat sheet: Open to print (every command, grouped by unit: a handout for the final challenge)

Shapes and movement

Draw on a canvas, make it move every frame, and make decisions.

Shapes and movement in 5 minutes (read before teaching this unit)

The idea in plain words

p5.js draws on a canvas: a rectangle of pixels where (0, 0) is the top left and y counts down. A sketch has two special functions that p5 runs for you. setup() runs once; draw() runs about 60 times a second, and each run is a frame. Movement is a small change to a variable every frame, drawn again where it now is. if and comparisons let the sketch decide, for example to turn round at an edge or to react to mouseX.

Why programmers use it

  • One loop for everything: games, animations and data pictures all repeat "change, then draw".
  • Variables as state: the values the sketch keeps between frames are how it remembers where things are.

An everyday picture, and where it breaks

A flick book: each page is a frame and the movement is the tiny change between them. It breaks because a flick book's pages are fixed, while draw() works out each page as it goes.

Try it yourself (5 minutes)

  1. Run the first sketch and change a number in circle(...).
  2. Move fill(...) below the shape. What happens, and why?
  3. Make a shape move by adding to a variable in draw().

Questions students ask

  • Why is my shape upside down? y counts down from the top, so a bigger y is lower on the canvas.
  • Why did the colour not change? fill only colours shapes drawn after it.
  • Where did my old picture go? background(...) at the start of draw() clears it each frame.

How it connects

This is turtle drawing and the events lesson in JavaScript: the same loops, variables and decisions, with a different way of saying them.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Building blocks

Lists and loops, objects, and functions of your own.

Lists, objects and functions in 5 minutes (read before teaching this unit)

The idea in plain words

Three tools for keeping a sketch short. An array is a list: [40, 90, 150], read by place (heights[0] is the first, because counting starts at 0). An object keeps the values of one thing together: { x: 20, y: 30, speed: 2 }, read with a dot (star.speed). A function is code with a name: you define it once and call it as often as you like, giving it values through parameters and getting an answer back with return. A list of objects, a loop over it, and a function that works on one object make the shape of most games.

Why programmers use it

  • Many things, one piece of code: a hundred stars are a list and a loop, not three hundred variables.
  • Names for ideas: drawFlower(x, y, size) says what the code is for.
  • One place to fix: change a function once and every call changes.

An everyday picture, and where it breaks

A recipe card: the recipe is written once (the definition) and cooked as many times as you like (the calls), with the amounts changed each time (the parameters). It breaks because a recipe is not cooked by writing it; a function does nothing until it is called.

Try it yourself (5 minutes)

  1. Run the stars sketch and add a size property to each star.
  2. Write a function that draws a face, then call it three times with different positions.
  3. Change one capital letter in a call. What does the error say?

Questions students ask

  • Why does it say speed is not defined? The speed belongs to the star: write star.speed.
  • Why does my function draw nothing? It is defined but never called.
  • What is i? The counter of a for loop: 0, then 1, then 2, and so on.

How it connects

These are the lists, objects (without classes) and functions of the Python units, in JavaScript. Next: the final challenge puts them all in one game.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Final challenge: Catch the circle

Build a click-to-catch game with a score, lives and a restart. One optional lesson makes moving art.

A game with a click in 5 minutes (read before teaching this unit)

The idea in plain words

An event function is one p5 calls when something happens: mousePressed() on each click, keyPressed() on each key. The game keeps a list of falling balls (objects). When the player clicks, the event function checks each ball: if dist(mouseX, mouseY, ball.x, ball.y) < 20 the click is close, so the score goes up and the ball restarts. A missed ball costs a life, and at zero lives the game shows GAME OVER until a key starts it again. The optional lesson uses sin, cos and map to make moving patterns.

Why programmers use it

  • Events are how every interactive program waits for people.
  • Distance checks decide what touched what in most 2D games.
  • Playtesting shows what is too hard, too easy or confusing.

An everyday picture, and where it breaks

A doorbell: nothing happens until someone presses it, and then a short piece of code runs. It breaks because the doorbell rings once, while draw() also keeps running between clicks.

Try it yourself (5 minutes)

  1. Play the game and change < 20 to < 40. Is it easier or harder?
  2. Add a lives variable and take one away when a ball falls off the bottom.
  3. Give one ball a property that makes it worth more points.

Questions students ask

  • Why does every click score? The test is probably > where it should be <.
  • Why does pressing R do nothing? Click the picture first so it receives the keys.
  • Why does the score jump by lots? The ball was not restarted, so it scores again.

How it connects

This is Catch the turtle in JavaScript, and a first game for the microStudio course. Beyond it: p5.js's own reference, or the DOM course for changing real web pages.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Open projects

Self-paced briefs students can pick up (after the lesson named on each, where one is named). Students tick their own milestones and claim a badge; the page lights the skills their code uses. Badges stay in the student's browser: ask them to press Show your teacher. Open the projects page

A night sky (after p5-lists; an array ([1, 2, 3]), .push(), a loop over a list (for (let x of list)), random())

Paint a night sky: a crowd of stars scattered at random, a moon, some ground, and stars that twinkle.

Milestones:

  • At least fifty stars at random places, made by one loop.
    1. A counting loop can run the same lines sixty times.
    2. Inside the loop, random picks a different place each time.
    Students can earn this piece (reveal on): for (let i = 0; i < 60; i++) {
    stars.push({ x: random(width), y: random(height * 0.7), size: random(1, 4) });
    }
  • Every star is kept in a list, and one loop draws them all.
    1. Make the list outside setup, so draw can use it too.
    2. In draw, a for-of loop gives you each star in turn.
  • The stars twinkle: their size changes a little as the sketch runs.
    1. draw runs again and again. If the size changes a little each time, the star seems to twinkle.
    2. sin of the frame count goes up and down smoothly. Add a little of it to the size.
    Students can earn this piece (reveal on): circle(s.x, s.y, s.size + 1 + sin(frameCount * 0.05 + s.x));

Builds on Lists of shapes (an array and a loop over it) and keeps each star as a small object, so s.x and s.y are recipes here. The twinkle is sin of the frame count; students can copy that line and change the numbers, which is enough. The moon is a pale circle with a night-coloured one over it: a good quick lesson in drawing order.

One possible solution
let stars = [];

function setup() {
  createCanvas(400, 300);
  noStroke();
  for (let i = 0; i < 60; i++) {
    stars.push({ x: random(width), y: random(height * 0.7), size: random(1, 4) });
  }
}

function draw() {
  background(15, 20, 50);
  fill(255, 245, 200);
  for (let s of stars) {
    circle(s.x, s.y, s.size + 1 + sin(frameCount * 0.05 + s.x));
  }
  fill(255, 250, 220);
  circle(330, 60, 40);
  fill(15, 20, 50);
  circle(342, 54, 36);
  fill(20, 40, 30);
  rect(0, 250, width, 50);
}
Bouncing balls (after p5-objects; an object ({ x: 5, y: 8 }), a property (star.y), a loop over a list (for (let x of list)), if)

Make a handful of balls that bounce around the canvas, each with its own colour and speed, and turn round whenever they hit a wall.

Milestones:

  • Several balls, each an object with its own place, speed and colour.
    1. An object holds a ball's own x, y, speed and colour in one place.
    2. A loop in setup can make a few of them with random values and push each onto a list.
    Students can earn this piece (reveal on): balls.push({
    x: random(40, 360), y: random(40, 260),
    dx: random(-3, 3), dy: random(2, 5),
    colour: color(random(80, 255), random(80, 255), random(80, 255)),
    });
  • One loop moves and draws every ball, every frame.
    1. In draw, a for-of loop visits every ball. Move it, then draw it.
  • Each ball turns back at a wall instead of leaving.
    1. When a ball gets close to a wall, its speed in that direction can flip to the other sign.
    2. Check the left and right walls for x, and the top and bottom for y. Remember that the ball has a size.
    Students can earn this piece (reveal on): if (b.x < 15 || b.x > width - 15) {
    b.dx = -b.dx;
    }

The same shape as Objects and stars with a new rule: when a ball reaches a wall, its speed flips sign. The test for each wall is one if and two sides joined with ||, which students often split into two checks; both work. If a ball seems to stick to a wall, ask where the edge test is and how far from the centre the edge really is.

One possible solution
let balls = [];

function setup() {
  createCanvas(400, 300);
  for (let i = 0; i < 6; i++) {
    balls.push({
      x: random(40, 360), y: random(40, 260),
      dx: random(-3, 3), dy: random(2, 5),
      colour: color(random(80, 255), random(80, 255), random(80, 255)),
    });
  }
}

function draw() {
  background(30);
  for (let b of balls) {
    b.x = b.x + b.dx;
    b.y = b.y + b.dy;
    if (b.x < 15 || b.x > width - 15) {
      b.dx = -b.dx;
    }
    if (b.y < 15 || b.y > height - 15) {
      b.dy = -b.dy;
    }
    fill(b.colour);
    circle(b.x, b.y, 30);
  }
}
A pattern maker (after p5-functions; a function of your own, a function with parameters, a counting loop (for (let i = 0; i < 6; i++)), random())

Write your own flower function that draws one flower anywhere, then use it in loops to cover the canvas with a pattern.

Milestones:

  • A function of your own that draws one flower, with its place and size as parameters.
    1. Write the flower so it draws around x and y, wherever they are.
    2. Whatever you want to change from one flower to the next goes in the brackets as a parameter.
    Students can earn this piece (reveal on): function flower(x, y, size) {
  • Loops call it to fill the canvas in rows and columns.
    1. One loop inside another gives you rows and columns.
    2. Work out the place from the row and column numbers, so each flower is further along than the last.
    Students can earn this piece (reveal on): for (let row = 0; row < 3; row++) {
    for (let col = 0; col < 4; col++) {
    flower(65 + col * 90, 60 + row * 90, random(20, 36));
    }
    }
  • Each flower has a size or colour of its own, using random.
    1. random gives a different number each time it runs, so calling it inside the loop makes each flower different.

Builds on Functions in p5.js: a function with parameters, called many times. The petals use cos and sin to place circles round a centre; students can copy that recipe and change the numbers, and the conversation is about what stays in the function and what is passed in. The picture is one run: the random sizes and colours make every run different.

One possible solution
function setup() {
  createCanvas(400, 300);
  background(255, 245, 230);
  noStroke();
  for (let row = 0; row < 3; row++) {
    for (let col = 0; col < 4; col++) {
      flower(65 + col * 90, 60 + row * 90, random(20, 36));
    }
  }
}

function flower(x, y, size) {
  fill(random(200, 255), random(80, 160), random(120, 200));
  for (let i = 0; i < 6; i++) {
    let angle = i * 60;
    circle(x + cos(radians(angle)) * size, y + sin(radians(angle)) * size, size);
  }
  fill(255, 220, 60);
  circle(x, y, size);
}