The Creative Coder’s Field Guide

Everything You Need to Survive and Thrive with p5.js

Creative Coding · Week 7

Cookie-CutterClasses, objects, constructors and methods in p5.js

Last week an object literal held a dot’s data, and separate functions moved it and drew it. This week you write a class: one definition that bundles the data and the functions together, then stamps out as many objects as you like. Combine it with an array and a sketch can run three thousand bouncing balls in a handful of lines.

Objects + classes · editor.p5js.org · Understand → Know → Do
01The idea

Why objects?

Picture a sketch with a truck and one function that draws it. One truck is easy. Two trucks need x1, y1, x2, y2. Three need six variables. Now give every truck a color and a speed, and the variable list is out of control.

Week 6 showed part of the fix. An object literal like { x: 40, y: 120, speed: 2 } keeps one truck’s facts together under one name. But the functions that move and draw it, like moveDot() and drawDot(), still lived outside, and every one of them needed the object handed in as an argument.

Objects encapsulate both data and code: the variables that describe a thing and the functions that work on it, in one package. A truck object knows its own position and speed, and it also knows how to move itself and draw itself. That makes your code better organized and easier to read, because everything about trucks lives in one place.

Writing code organized around objects like this is called object-oriented programming. In JavaScript, you describe a kind of object once with a class, then create as many objects from it as you need.

02Vocabulary

The cookie cutter and the cookies

A handful of new words come with objects. The picture Dan Shiffman uses in the Coding Train videos is the one to keep in your head: a class is a cookie cutter, and objects are the cookies.

CLASS · the cookie cutter BouncingBall colorsizex, yvx, vy move()drawIt() OBJECTS · the cookies color "#ff0000"size 100, x 212 … color "#9C27B0"size 12, x 57 … color "#00BCD4"size 25, x 330 … new
The class says what every ball has and can do. Each object has its own values: three balls, three colors, three sizes, three positions, one definition.
class
the template for a kind of object: the cookie cutter. You define a class once.
object
one thing made from a class: a cookie. Also called an instance of the class.
instantiate
to create an object from a class, using the new keyword
constructor
a special function inside a class that runs once to set up each new object
property
a variable that belongs to an object, like this.x (the same idea as an object literal’s keys)
method
a function that belongs to an object, like drawIt()
03Defining a class

Defining a class and making an object

Here’s the smallest possible version: an empty class, and one object made from it. It doesn’t do anything yet, but every class you write has this shape.

// A variable that will hold the object once it's created
let myBouncingBall;

// A class is like a template that defines code and variables
//    for an object that can be reused.
class BouncingBall {
  // everything that it means to be a BouncingBall
}

function setup() {
  // Create (instantiate) an object from the class
  myBouncingBall = new BouncingBall();
}
keyword name: Capitalized class BouncingBall { constructor(aColor, aSize) { … } drawIt() { … } move() { … } } constructor sets up each object methods no "function" ball = new BouncingBall("#ff0000", 100); instantiate: new + class name + arguments for the constructor
Class names start with a capital letter (BouncingBall, Robot, TextDroplet) so they stand out from variables and functions, which start lowercase. The object goes in an ordinary lowercase variable.
  • Define classes on their own, outside setup() and draw(), like your Week 5 functions.
  • Define the class above the code that uses it, or in its own file (section 07). Unlike a function, a class can’t be used before the line that defines it has run.
  • Create objects in setup() or later, not at the top of the sketch. Constructors often use width, height or random(), which aren’t ready until p5 has started (the same reason as Week 2’s house pattern).
04Methods

Teaching an object to do something

A function inside a class is called a method. Let’s teach the BouncingBall how to draw itself. Inside a class you leave off the word function; just write the name, parentheses and braces.

let myBouncingBall;

class BouncingBall {
  // a method (function) the BouncingBall can use to draw itself
  drawIt() {
    // put code here to draw the ball
  }
}

function setup() {
  createCanvas(400, 400);
  myBouncingBall = new BouncingBall();
}

function draw() {
  background(220);
  // to draw the ball, call its drawIt() method
  myBouncingBall.drawIt();
}

To call a method, write the object, a dot, then the method call: myBouncingBall.drawIt(). Read it as “myBouncingBall, draw it.” You’re asking that particular object to do something.

You’ve seen this dot before. Week 6’s myArray.push(10) and myStr.split("") are method calls too. Every JavaScript array is an object made from a built-in class called Array, and push() is one of its methods.

05Constructor & this

The constructor gives each object its own data

The constructor is a special method, always named constructor, that runs once, automatically, when you write new. Its job is to set up the new object. Arguments you pass to new arrive as the constructor’s parameters.

class MyClass {
  constructor(ax, ay) {
    // ax and ay only exist inside the constructor,
    //   so copy them into variables that belong to the object.
    this.x = ax;     // "this." means this.x is part of the object
    this.y = ay;
  }

  myMethod() {
    circle(this.x, this.y, 25);   // uses the x and y set in the constructor
  }
}

let myObject;

function setup() {
  createCanvas(400, 400);
  myObject = new MyClass(100, 100);   // 100, 100 go to the constructor
}

function draw() {
  myObject.myMethod();
}

What this means

Parameters like ax are local: they vanish when the constructor finishes (Week 5). To keep a value, the constructor stores it as a property of the object with this. in front. Inside a class, this means “the object this code is running for.” Because each object has its own this, each one gets its own x and y, and any method can use them later.

1 · the call new BouncingBall("#ff0000", 100) 2 · constructor runs constructor(aColor, aSize) { this.color = aColor; this.size = aSize; this.x = random(0, width); … } arguments → parameters 3 · the new object this.color: "#ff0000" this.size: 100 this.x: 212.4 this.y: 87.9 this.vx: 3.1 this.vy: 6.6 (random values vary)
The parameters aColor and aSize disappear when the constructor ends. Their values survive as this.color and this.size, stored in the object.

Here’s the BouncingBall with a constructor. Its color and size come from the arguments; its position and speed are picked at random, so every ball is different:

class BouncingBall {
  constructor(aColor, aSize) {
    this.color = aColor;
    this.size = aSize;
    this.x = random(0, width);
    this.y = random(0, height);
    this.vx = random(0.5, 8);
    this.vy = random(0.5, 8);
  }

  drawIt() {
    fill(this.color);
    circle(this.x, this.y, this.size);
  }
}

// in setup():
myBouncingBall = new BouncingBall("#ff0000", 100);

Forgetting this. is the number-one class bug. Inside a method, plain x is not the same as this.x. Plain x looks for a local or global variable named x, finds none (or the wrong one), and you get an error, NaN, or a ball stuck in the wrong place. If a property “isn’t working”, check every use has this. in front.

06The whole ball

Methods working together

A class can have as many methods as it needs, and they can take parameters just like Week 5 functions. Methods can call each other too. From outside the object you call a method with the object’s variable; from inside, you use this.:

class MyClass {
  constructor(ax, ay) {
    this.myMethod(20, 20);   // calling a method from inside: this.
  }

  myMethod(p1, p2) {
    // do something
  }
}

// in draw():
myObject.myMethod(20, 25);   // calling it from outside: the object's name

The final BouncingBall

This class is responsible for both moving and drawing the ball. move() adds the speeds to the position and reverses a speed when the ball reaches an edge (Week 3’s if and ||). drawIt() calls this.move() first, so one call from draw() does everything.

sketch.js

class BouncingBall {
  constructor(aColor, aSize) {
    this.color = aColor;
    this.size = aSize;
    this.x = random(0, width);
    this.y = random(0, height);
    this.vx = random(0.5, 8);
    this.vy = random(0.5, 8);
  }

  move() {
    this.x += this.vx;
    this.y += this.vy;

    if ((this.x > width) || (this.x < 0)) {
      this.vx *= -1;
    }
    if ((this.y > height) || (this.y < 0)) {
      this.vy *= -1;
    }
  }

  drawIt() {
    this.move();
    fill(this.color);
    circle(this.x, this.y, this.size);
    fill("#000000");
    circle(this.x, this.y, this.size / 2);
  }
}

// Variables that will hold our objects once they're created
let myBouncingBall1;
let myBouncingBall2;

function setup() {
  createCanvas(400, 400);
  myBouncingBall1 = new BouncingBall("#ff0000", 100);
  myBouncingBall2 = new BouncingBall("#9C27B0", 12);

  // print the objects to see their properties in the console
  print(myBouncingBall1);
  print(myBouncingBall2);
}

function draw() {
  background(220);
  myBouncingBall1.drawIt();
  myBouncingBall2.drawIt();
}

Look at how little draw() has to know. It doesn’t touch x, vx or the edge checks; it just asks each ball to draw itself. Each ball keeps its own numbers, so the big red ball and the small purple one bounce independently.

Printing an object (Week 2’s print()) shows every property and its current value in the console. It’s the fastest way to check what the constructor actually set up.

07Its own file

Give the class its own file

As a class grows, sketch.js gets long. In the review we moved the BouncingBall class into its own file, ball.js, so sketch.js only holds setup() and draw(). Each file has one job, the same reason we split code into functions.

  1. In the p5 editor, open the file list (the > arrow above your code), click +, choose Create file, and name it ball.js.
  2. Cut the whole class out of sketch.js and paste it into ball.js.
  3. Open index.html and add a line that loads the new file, before the line that loads sketch.js:

index.html — inside <body>

<script src="ball.js"></script>
<script src="sketch.js"></script>

Order matters here too. The browser loads the files top to bottom. If sketch.js loads first, it tries to use BouncingBall before the class exists and you’ll get an error like “BouncingBall is not defined”. (Week 8 explains what index.html and these <script> tags are.)

08Arrays of objects

Three thousand balls

Two balls need two variables. Four need four. Thousands? Put them in an array (Week 6). Three steps:

  1. Create an empty array instead of individual variables to hold the BouncingBall objects.
  2. In setup(), use a loop to create thousands of ball objects and push() each one into the array.
  3. In draw(), use another loop to call drawIt() on each ball.

sketch.js

/* Originally we created four variables:
let myBouncingBall1;
let myBouncingBall2;
let myBouncingBall3;
let myBouncingBall4;
   Since we need thousands of balls, let's use an array instead. */
let ballArray = [];

// an array of colors to choose from
let myColors = ["#4e4187", "#30c5ff", "#f9e0d9", "#b26e63", "#cec075"];

function setup() {
  createCanvas(400, 400);

  // Create 3000 BouncingBall objects and push each one into ballArray,
  //   with a random color from myColors and a random size
  for (let i = 0; i < 3000; i++) {
    ballArray.push(new BouncingBall(random(myColors), random(2, 10)));
  }
}

function draw() {
  background(220);

  // Loop through the array and ask each ball to draw itself
  for (let i = 0; i < ballArray.length; i++) {
    ballArray[i].drawIt();
  }
}
ballArray ball ball ball ball … 0 1 2 2999 ballArray[i].drawIt() the object at index i, draw yourself
Compare with Week 6’s object literals, where the loop needed moveDot(dots[i]) and drawDot(dots[i]). The object now carries its own methods, so the loop just asks it to act.

The class didn’t change at all between two balls and three thousand. That’s the payoff of objects: the class handles what one ball does, and the array and loop handle how many.

09Text rain

Example: text rain

This example from a prior semester builds the falling “digital rain” from the Matrix films in steps, combining everything so far: Week 6’s vertical-text trick with split() and join(), a class, and an array.

  1. Make the text vertical (Week 6, section 06).
  2. Create a TextDroplet class that keeps track of its string on the canvas, displays it vertically and controls how it falls.
  3. Use two variables to keep track of two droplets.
  4. Replace the two variables with a single array of droplets.

The TextDroplet class

class TextDroplet {
  constructor(x, y, aText) {
    this.x = x;
    this.y = y;
    this.myText = aText;
    this.speed = random(1, 6);
  }

  draw() {
    // Make the text vertical with a line feed between each character
    let myStr = this.myText.split("").join("\n");
    textSize(15);
    textStyle(BOLD);
    fill("#0E740E");
    text(myStr, this.x, this.y);

    this.y += this.speed;
    if (this.y > height) {
      this.y = -150;     // back above the top, ready to fall again
    }
  }
}

A method can be called draw() even though p5 has a draw() function: myDrop1.draw() belongs to the droplet, so the two never get confused. Notice also that myStr is a plain local variable. It’s only needed while the method runs, so it doesn’t get this..

Two droplets, then many

let myDrop1;
let myDrop2;

function setup() {
  createCanvas(400, 400);
  myDrop1 = new TextDroplet(random(0, width), random(0, height), "Hello Code!");
  myDrop2 = new TextDroplet(random(0, width), random(0, height), "Hello Code!");
}

function draw() {
  background(220);
  myDrop1.draw();
  myDrop2.draw();
}
// Instead of a separate variable for each drop,
//   one array holds them all. We fill it in setup().
let myDrops = [];

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < 50; i++) {
    myDrops.push(new TextDroplet(int(random(0, 20)) * 20, random(0, height), "Hello Code!"));
  }
}

function draw() {
  background(0);   // black, like the films
  for (let i = 0; i < myDrops.length; i++) {
    myDrops[i].draw();
  }
}

The x position int(random(0, 20)) * 20 picks a whole number from 0 to 19 and multiplies it by 20, so the droplets line up in 20 neat columns instead of landing anywhere. (int() chops off the decimal part.)

10Robots

Example: a thousand robots

The Week 5 robot makes a natural class. Its parameters, x, y, color and scale, become properties set in the constructor, and drawRobot() becomes a method. Here’s a sketch of the conversion; the full example sketch also gives each robot its own movement:

class Robot {
  constructor(x, y, s) {
    this.x = x;
    this.y = y;
    this.s = s;
    this.bodyColor = color(random(255), random(255), random(255));
  }

  drawSelf() {
    push();
    translate(this.x, this.y);
    scale(this.s);
    fill(this.bodyColor);
    rect(50, 40, 20);         // neck
    circle(60, 20, 40);       // head
    rect(30, 60, 60, 100);    // body
    // … arms and legs, as in Week 5
    pop();
  }
}

And the sketch that makes a thousand of them follows exactly the same pattern as the balls and the droplets:

let robotCount = 1000;
let myRobots = [];

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < robotCount; i++) {
    myRobots.push(new Robot(200, 200, 0.5));
  }
}

function draw() {
  background(220);
  for (let i = 0; i < myRobots.length; i++) {
    myRobots[i].drawSelf();
  }
}

Spot the pattern. Balls, droplets, robots: the sketch always has the same three parts. A class describes one thing. A loop in setup() pushes many new objects into an array. A loop in draw() calls a method on each one. Once you see that shape, you can build a crowd of anything.

11Reference

Quick reference

Class template

class ClassName {
  constructor(param1, param2) {
    this.prop1 = param1;           // properties: this.something
    this.prop2 = param2;
  }

  methodName() {
    // use this.prop1, this.prop2
    this.otherMethod();            // call another method from inside
  }

  otherMethod() { … }
}

let obj = new ClassName(10, 20);   // instantiate
obj.methodName();                  // call a method
obj.prop1                          // read a property from outside

The crowd pattern

let things = [];

function setup() {
  for (let i = 0; i < 100; i++) {
    things.push(new Thing());
  }
}

function draw() {
  for (let i = 0; i < things.length; i++) {
    things[i].drawIt();
  }
}
WordMeansExample
classtemplate for a kind of objectclass BouncingBall { … }
object / instanceone thing made from a classmyBouncingBall1
instantiatecreate an objectnew BouncingBall("#ff0000", 100)
constructorsets up each new objectconstructor(aColor, aSize) { … }
propertya variable belonging to an objectthis.x
methoda function belonging to an objectdrawIt() { … }
thisthe object the code is running forthis.x += this.vx;
12Practice

Be able to do

Name the parts

In this code, find the class name, the constructor, each property, each method, the line that instantiates an object, and the line that calls a method (sections 02 to 05).

class Firefly {
  constructor(ax, ay) {
    this.x = ax;
    this.y = ay;
    this.glow = 0;
  }
  blink() {
    this.glow = random(100, 255);
  }
  show() {
    fill(255, 255, 0, this.glow);
    circle(this.x, this.y, 8);
  }
}

let fly;
function setup() {
  createCanvas(400, 400);
  fly = new Firefly(200, 200);
}
function draw() {
  background(0);
  fly.blink();
  fly.show();
}

Class: Firefly. Properties: x, y, glow. Methods: blink(), show(). Instantiate: fly = new Firefly(200, 200). Method calls: fly.blink() and fly.show().

Find the bug

This ball never moves and the console shows no error. Why? (Section 05.)

class Ball {
  constructor(ax, ay) {
    this.x = ax;
    this.y = ay;
    this.speed = 3;
  }
  move() {
    let x = this.x;
    x += this.speed;
  }
  show() {
    circle(this.x, this.y, 20);
  }
}

move() copies this.x into a local variable x and changes the copy. The object’s own this.x never changes. The fix is this.x += this.speed;.

From literal to class

Take your confetti sketch from Week 6 (or the falling dots in Week 6, section 08) and turn it into a Confetti class. The object literal’s properties become this. properties set in the constructor; moveDot() and drawDot() become methods. When you’re done, the loop in draw() should be a single line.

Two files

Move your Confetti class into its own file, confetti.js, and load it from index.html (section 07). Then swap the two <script> lines and read the error you get. Put them back.

Your character, a hundred times

Turn the character you built in Week 5 into a class with a constructor that takes x, y and a scale, and a drawSelf() method that uses push(), translate() and scale() (section 10). Give each one a random speed and a move() method that wraps it around the edges. Fill an array with 100 of them.

Rain of your own words

Change the text rain (section 09) so each droplet gets a different word. Make an array of at least eight words, and pass random(myWords) to the constructor instead of "Hello Code!". Then give each droplet its own green from an array of greens.

Pop them (stretch)

Add a method isUnder(mx, my) to the BouncingBall that returns true when the point is inside the ball (use dist() and compare with half the size). When the mouse is pressed, remove every ball under the mouse with splice(i, 1). Hint: loop through the array backwards, from ballArray.length - 1 down to 0. Week 6’s splice diagram shows why going forwards would skip a ball.