← Teacher guide Markdown for Prepare

Building blocks: cheat sheet

Drawing and animation with p5.js · In any playground, open Reference to copy these.

array

Makes a list. The first item is heights[0], because counting starts at 0.

let heights = [40, 90, 150];
Example
let heights = [40, 90, 60, 100];

function setup() {
  createCanvas(200, 130);
  background(235);
  for (let i = 0; i < heights.length; i++) {
    rect(25 + i * 42, 120 - heights[i], 30, heights[i]);
  }
}
What it draws

for of

Does the code once for each item of a list, with star as that item.

for (let star of stars) {
  ...
}

random

A random number from the first number up to (not including) the second.

random(10, 100)

object

Keeps the values of one thing together, each with a name.

let star = { x: 20, y: 30, speed: 2 };

function

Gives code a name. The names in the brackets are parameters. It runs only when called: drawFlower(80, 100);

function drawFlower(x, y) {
  ...
}

array item

One item of a list, by its place.

heights[0]

length

How many items are in a list.

heights.length

push

Adds an item to the end of a list.

heights.push(120);

for count

Repeats the code in the braces, with i counting 0, 1, 2, ... up to one less than 6.

for (let i = 0; i < 6; i++) {
  ...
}
Example
function setup() {
  createCanvas(200, 130);
  background(235);
  for (let i = 0; i < 5; i++) {
    circle(30 + i * 35, 65, 28);
  }
}
What it draws

property

Reads one value of an object with a dot. Change it the same way: star.y = star.y + 1;

star.y