The Creative Coder’s Field Guide
Everything You Need to Survive and Thrive with p5.js
Creative Coding · Week 5
You’ve been calling functions since your first rect(). This week you write your own: wrap a drawing in a name, hand it numbers so it can be drawn anywhere, and use translate(), rotate() and scale() to move, spin and resize whole groups of shapes at once. Then one robot becomes a hundred.
A function takes a chunk of code, gives it a name, and lets you run the whole chunk by saying that name. Programming with functions is one of the easiest ways to break your code into usable, and reusable, blocks.
Functions make programs smaller (write the code once, run it as often as you like), better organized (each block does one job), and easier to understand (drawRobot(); tells a reader far more than twenty lines of rect() calls). Organizing your code into functions like this is a big part of writing code you can maintain, and it’s how almost every larger program is built.
rect(20, 20, 30) calls a function named rect and passes it the three numbers it needs to draw a square. fill(), background() and print() are functions too.function setup() { … } and function draw() { … }. Those are functions you wrote. They’re special because p5 calls them for you automatically: setup() once at the start, draw() every frame (Week 1).This week you’ll define functions that nobody calls automatically. They sit quietly until your code calls them by name.
Functions are easiest to understand by improving a sketch you already know how to write. Here’s a robot built from seven shapes, all inside draw(), with a comment naming each body part:
sketch.js
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Draw Robot
// Draw Neck
rect(50, 40, 20);
// Draw Head
circle(60, 20, 40);
// Draw Body
rect(30, 60, 60, 100);
// Draw Arms
rect(-10, 60, 40, 20);
rect(90, 60, 40, 20);
// Draw Legs
rect(30, 160, 20, 40);
rect(70, 160, 20, 40);
}
Run the robot in the p5 editor
x = -10, which is why part of it hangs off the edge.This sketch works, but it has three problems that get worse as a sketch grows:
draw() is already long, and it only draws one thing.The rest of this guide fixes all three, one step at a time.
Working with your own function has two halves. The definition creates the function and says what it does. The call runs it. Here’s the simplest shape: a function that takes nothing in and does some work.
setup() and draw(). The name is yours to choose, using the same camelCase care as your variables (Week 2). Verb names like drawRobot read best because a function does something.The general pattern:
function yourFunctionName() {
// a bunch of code to do stuff
}
function draw() {
// To call your function, just use its name
// with parentheses
yourFunctionName();
}
Cut the seven shape lines out of draw(), paste them into a new function named drawRobot, and put a single call where they used to be. The picture on the canvas doesn’t change at all. The code is just organized better.
sketch.js
function draw() {
background(220);
drawRobot();
}
function drawRobot() {
rect(50, 40, 20); // neck
circle(60, 20, 40); // head
rect(30, 60, 60, 100); // body
rect(-10, 60, 40, 20); // left arm
rect(90, 60, 40, 20); // right arm
rect(30, 160, 20, 40); // left leg
rect(70, 160, 20, 40); // right leg
}
Run the basic drawRobot() function
p5 still reads draw() top to bottom (Week 1). When it reaches drawRobot(); it jumps into the function, runs its body top to bottom, then jumps back and carries on with the next line of draw().
Three mistakes to watch for.
function drawRobot() { … } on its own, next to setup() and draw(), not inside their braces. Tidy Code makes this easy to see: every definition should start at the left edge.drawRobot; without () just mentions the function and runs nothing. No error, no robot.print("drawRobot ran") inside the body will tell you (Week 2).drawRobot() always draws the same robot in the same place. rect() is more useful because you hand it numbers and it uses them. Your own functions can do the same thing. Two words to keep straight:
Here’s a function with three parameters:
// Three parameters: ax, ay and aw
function functionToDrawBlueSquare(ax, ay, aw) {
fill(0, 0, 200);
rect(ax, ay, aw);
}
function draw() {
// Call it by name, with parentheses, and pass 3 arguments
functionToDrawBlueSquare(100, 100, 50);
// We can call it a second time with different arguments
functionToDrawBlueSquare(200, 200, 74);
}
ax = 100, ay = 100, aw = 50. The second call starts fresh with ax = 200, ay = 200, aw = 74.functionToDrawBlueSquare(mouseX, mouseY, width / 8) works fine. Each expression is worked out to a number first, then passed in (Week 2’s Expressions section).Count your arguments. If you pass fewer arguments than there are parameters, the leftovers hold undefined. Any math with undefined gives NaN (“not a number”), and a shape drawn at NaN silently doesn’t appear. If shapes vanish after you add a parameter, check every call.
To move the robot, give drawRobot two parameters, x and y, and add them to every coordinate. The robot’s own numbers become offsets from an anchor point. Change the anchor and the whole formation moves together. That’s the relationship idea from Week 2: draw things relative to one point instead of at fixed spots.
While we’re at it, a third parameter lets each robot have its own color. color() packs red, green and blue into a single value that you can store in a variable and pass around.
sketch.js
function draw() {
background(220);
drawRobot(40, 100, color(210, 30, 92));
drawRobot(220, 150, color(11, 124, 141));
}
function drawRobot(x, y, bodyColor) {
fill(bodyColor);
rect(x + 50, y + 40, 20); // neck
circle(x + 60, y + 20, 40); // head
rect(x + 30, y + 60, 60, 100); // body
rect(x + -10, y + 60, 40, 20); // left arm
rect(x + 90, y + 60, 40, 20); // right arm
rect(x + 30, y + 160, 20, 40); // left leg
rect(x + 70, y + 160, 20, 40); // right leg
}
Run robots with position and color parameters
Notice that only the positions get x + and y +. The widths and heights stay the same, because a robot doesn’t get wider when you move it to the right.
Now draw two robots, ten, or one that follows mouseX and mouseY. The function doesn’t care where its numbers come from.
It works, but look at all those x +s. Fourteen small additions, each one a chance for a typo. Section 07 shows a cleaner way: move the whole canvas once with translate() and leave the original numbers alone.
So far our functions do something: they draw. A function can also work something out and hand the result back to whoever called it. The keyword for that is return.
function myFunctionToAddThreeNumbers(p1, p2, p3) {
return p1 + p2 + p3; // return sends the result back
}
function draw() {
let mySum = myFunctionToAddThreeNumbers(12, 8, 10);
// mySum will equal 30
}
width / 2 becomes a number (Week 2). So it can go anywhere a number can.You’ve met built-in functions that return things already: color(210, 30, 92) in section 05 doesn’t draw anything. It hands back a color value, which we passed straight into drawRobot(). Your own functions can be used the same way:
function double(n) {
return n * 2;
}
circle(200, 200, double(30)); // a 60-pixel circle
print(double(double(5))); // 20: calls can nest
| Kind | What it does | Example | Called as |
|---|---|---|---|
| Does something | draws, prints, changes a variable | drawRobot(40, 100, c) | a complete statement |
| Returns something | works out a value and hands it back | double(30) | part of a bigger statement |
Two things about return. It ends the function immediately: any lines after it in the body never run. And the value it sends back has to be caught. A line that’s only double(30); works out 60 and throws it away. Store it with =, pass it as an argument, or print it.
The three common transformations are translate(), rotate() and scale(). They don’t change any shape directly. They change the coordinate system that every following shape is drawn in.
translate(x, y) moves the origin, the (0,0) point. Everything drawn after the translate is measured from the new origin, so it lands in a new position.
translate() as sliding the paper under your pen. Your pen still draws at the same numbers; the paper moved.translate() inside draw(), each one works on top of the changes from the one before. translate(50, 0) twice puts the origin at (100, 0), not (50, 0).draw() finishes, all transformations are set back to the original settings, as if there had never been any. That’s why a translate() in draw() doesn’t drift further every frame.With translate(), the robot function no longer needs x + and y + in every shape. Move the origin to (x, y) once, then draw the robot with its original numbers:
function drawRobot(x, y, bodyColor) {
translate(x, y); // the robot's (0,0) is now at (x, y)
fill(bodyColor);
rect(50, 40, 20);
circle(60, 20, 40);
rect(30, 60, 60, 100);
// … arms and legs, unchanged
}
Try calling this twice, though, and the second robot ends up in the wrong place: its translate is added to the first one’s. Section 09 fixes that with push() and pop().
rotate() works the same way as translate(): it turns the whole coordinate grid, and everything drawn afterwards comes out turned. It always rotates around the current (0,0) point.
The angle is in radians, not degrees. PI (about 3.1415) is 180°, and TWO_PI is a full 360° turn. If you’d rather think in degrees, put this line in setup():
angleMode(DEGREES); // now rotate(90) means a quarter turn
PI / 6 is 30°. To spin a shape around its own middle, translate() to where its center should be, rotate(), then draw it centered on (0,0): for a rectangle, rect(-w / 2, -h / 2, w, h).Order matters. translate() then rotate() spins the shape in place. rotate() then translate() turns the grid first, so the translate slides along the tilted axes and the shape ends up somewhere else. When a transformed shape lands in an odd spot, read your transformations top to bottom and picture the grid moving at each step.
scale() makes everything drawn afterwards bigger or smaller. With one argument the whole grid scales evenly: scale(2) doubles everything, scale(0.5) halves it. With two, the first scales the x direction and the second scales the y direction.
scale(-1, 1) mirrors left to right. To make y count upward like a math graph, use translate(0, height) and then scale(1, -1); without the translate, everything flips up off the top of the canvas.scale(3), a 1-pixel stroke is drawn 3 pixels thick.Because every transformation builds on the one before, things get confusing fast. push() saves the current state of the transformations (even if that state is “no transformations”). pop() brings everything back to the state that was saved by the matching push(). They also save and restore drawing styles like fill(), stroke() and strokeWeight().
push(); // save: origin at the corner, no rotation
translate(200, 200);
rotate(PI / 4);
rect(-25, -25, 50, 50); // a diamond in the middle
pop(); // restore: back to the corner, unrotated
rect(10, 10, 50, 50); // a plain square at the top-left, unaffected
This is the version from the review: wrap the inside of the function in push() and pop(), use translate() for position, and add a scale() parameter for size. Every call cleans up after itself, so robots never disturb each other, and the shape lines keep their original, readable numbers.
sketch.js
function drawRobot(x, y, bodyColor, s) {
push();
translate(x, y);
scale(s);
fill(bodyColor);
rect(50, 40, 20); // neck
circle(60, 20, 40); // head
rect(30, 60, 60, 100); // body
rect(-10, 60, 40, 20); // left arm
rect(90, 60, 40, 20); // right arm
rect(30, 160, 20, 40); // left leg
rect(70, 160, 20, 40); // right leg
pop();
}
Run drawRobot() with translate and scale
Always in pairs. Every push() needs a pop(), in the same function, after it. A push() without a pop() leaves its transformations behind for everything drawn later. Indenting the lines between them, as you would inside braces, makes a missing pop() easy to spot.
Now that a single call places a robot anywhere, at any size, you can put a call inside a loop (Week 4) and let the loop variable supply the position. This draws a line of robots, looping through different values of x:
for (let x = 30; x < 400; x += 70) {
drawRobot(x, 100, color1, 0.4);
}
Two nested loops, one for y and one for x, fill the canvas with a grid of robots:
function draw() {
background(220);
for (let y = 30; y < 400; y += 90) {
for (let x = 30; x < 400; x += 70) {
drawRobot(x, y, color1, 0.4);
}
}
}
At a scale of 0.4 each robot is about 56 pixels wide and 80 tall, which is why the steps are 70 and 90: a robot plus a little gap.
Finally, an if statement (Week 3) can choose a different argument for different robots. Here the left half of the grid gets one color and the right half another:
for (let y = 30; y < 400; y += 90) {
for (let x = 30; x < 400; x += 70) {
let c;
if (x < 200) {
c = color1;
} else {
c = color2;
}
drawRobot(x, y, c, 0.4);
}
}
Run the grid of robots with conditional colors
Here color1 and color2 are global variables, declared at the top of the sketch and given values in setup() with color() (the house pattern from Week 2). Later in the course, arrays will make giving each robot its own color much easier.
Because drawRobot() takes its position as arguments, animating robots is just a matter of passing values that change every frame, like mouseX, frameCount, or a variable you update in draw().
| Word | Means | Example |
|---|---|---|
| definition | creates the function and its body | function drawRobot() { … } |
| call | runs the function | drawRobot(); |
| parameter | a variable named in the definition | x in drawRobot(x, y) |
| argument | a value passed in the call | 40 in drawRobot(40, 100) |
| return value | the value a function hands back | return n * 2; |
| transformation | a change to the coordinate grid | translate(), rotate(), scale() |
function name() { … } // no parameters
function name(a, b, c) { … } // three parameters
function name(a, b) { return a + b; } // returns a value
name(); // call, no arguments
name(10, 20, 30); // call with three arguments
let result = name(10, 20); // catch the return value
| Function | Does | Note |
|---|---|---|
translate(x, y) | moves the origin to (x, y) | adds to earlier translates |
rotate(angle) | turns the grid around (0, 0) | radians unless angleMode(DEGREES) |
scale(s) | grows or shrinks everything | 1 = normal, 2 = double, 0.5 = half |
scale(sx, sy) | scales x and y separately | negative flips that axis |
push() | saves transformations and styles | always pair with pop() |
pop() | restores what push() saved | |
angleMode(DEGREES) | switches angles to degrees | put it in setup() |
PI, HALF_PI, TWO_PI | 180°, 90°, 360° in radians | built-in constants |
All transformations reset when draw() ends.
In this code, point to every parameter and every argument (section 04). Then say what values w and h hold during the second call.
function drawWindow(wx, wy, w, h) {
rect(wx, wy, w, h);
line(wx + w / 2, wy, wx + w / 2, wy + h);
}
function draw() {
drawWindow(50, 50, 80, 120);
drawWindow(200, 60, 100, mouseY);
}
Parameters: wx, wy, w, h. Arguments: the numbers and mouseY in the calls. In the second call, w is 100 and h is whatever mouseY is that frame.
Design a character of your own (a creature, a car, a house) from at least six shapes, drawn directly in draw() with a comment for each part, like the robot in section 02. Then move every shape into a function called drawCharacter() and call it from draw(). The canvas should look exactly the same before and after.
Now call it twice. Why do you only see one character?
Add x and y parameters to drawCharacter() using anchor and offsets (section 05). Draw three characters in three different places, then make a fourth follow the mouse with drawCharacter(mouseX, mouseY). Which part of your character lands exactly on the mouse, and why?
Before running it, write down what each print() shows (section 06):
function mystery(a, b) {
return a * 2 + b;
}
print(mystery(3, 4));
print(mystery(4, 3));
print(mystery(mystery(1, 1), 0));
10, 11 and 6. Swapping the arguments changes the answer because they’re matched by position. In the last line the inner call runs first and returns 3, so the outer call is mystery(3, 0).
Rewrite drawCharacter() to match the finished robot in section 09: parameters x, y, a color, and a scale s; push(), translate(x, y), scale(s), the shapes with their original numbers, then pop(). Draw a big one, a small one and a medium one side by side.
Then delete the pop() and run it again. Describe what goes wrong and explain it in one sentence.
Use nested loops to fill the canvas with a grid of your characters (section 10). Pick the scale and step sizes so they don’t overlap. Then add an if so that every character in the top row is a different color from the rest.
Make one character slowly rotate around its own center (section 08). Use angleMode(DEGREES) in setup() and rotate(frameCount) for the angle. Hint: inside your push()/pop(), translate to where the character’s center should be, rotate, then translate back by half the character’s width and height before drawing the shapes. If it orbits instead of spinning, check the order of your transformations.