The Creative Coder’s Field Guide
Everything You Need to Survive and Thrive with p5.js
Creative Coding · Week 7
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.
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.
Run three trucks without objects
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.
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.
new keywordthis.x (the same idea as an object literal’s keys)drawIt()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();
}
BouncingBall, Robot, TextDroplet) so they stand out from variables and functions, which start lowercase. The object goes in an ordinary lowercase variable.setup() and draw(), like your Week 5 functions.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).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.
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();
}
this meansParameters 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.
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.
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
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();
}
Run the BouncingBall from the review
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.
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.
ball.js.sketch.js and paste it into ball.js.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.)
Two balls need two variables. Four need four. Thousands? Put them in an array (Week 6). Three steps:
setup(), use a loop to create thousands of ball objects and push() each one into the array.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();
}
}
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.
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.
TextDroplet class that keeps track of its string on the canvas, displays it vertically and controls how it falls.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..
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.)
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();
}
}
Run another robots class example
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.
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
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();
}
}
| Word | Means | Example |
|---|---|---|
| class | template for a kind of object | class BouncingBall { … } |
| object / instance | one thing made from a class | myBouncingBall1 |
| instantiate | create an object | new BouncingBall("#ff0000", 100) |
| constructor | sets up each new object | constructor(aColor, aSize) { … } |
| property | a variable belonging to an object | this.x |
| method | a function belonging to an object | drawIt() { … } |
this | the object the code is running for | this.x += this.vx; |
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().
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;.
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.
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.
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.
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.
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.