The Creative Coder’s Field Guide

Everything You Need to Survive and Thrive with p5.js

Creative Coding · Week 5

Building-BlocksCustom functions, parameters and transformations in p5.js

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.

Functions + transformations · editor.p5js.org · Understand → Know → Do
01The idea

A function is a named block of code

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.

You already use functions in two ways

  • You call them. Almost everything p5 does is a function. 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.
  • You define them. Every sketch you’ve written contains 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.

02The robot

Start with a drawing that works

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);
}
(0,0) 50 100 50 100 200 head circle(60, 20, 40) neck rect(50, 40, 20) arms rect(−10, 60, 40, 20) rect(90, 60, 40, 20) body rect(30, 60, 60, 100) legs y from 160 to 200 off canvas
Every number is measured from the canvas’s top-left corner, so the robot is stuck there. The left arm starts at 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.
  • A second robot means copying all seven lines and changing every number by hand.
  • The robot can only live in one spot. To move it, you edit fourteen coordinates.

The rest of this guide fixes all three, one step at a time.

03Defining

Define it once, call it by name

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.

keyword name parentheses function drawRobot() { circle(60, 20, 40); rect(30, 60, 60, 100); } body runs each time the function is called drawRobot(); ← the call: the name, then ()
Same braces-and-indentation grammar as 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();
}

Step one for the robot: move the shapes into a function

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
}

What happens when the call runs

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().

function draw() { background(220); drawRobot(); circle(300, 300, 50); } function drawRobot() { rect(50, 40, 20); circle(60, 20, 40); rect(30, 60, 60, 100); … } 1 · jump in 2 · jump back to the next line
This is why the robot is drawn on top of the background but under the circle: order still decides what’s on top, even when part of the order lives in another function.

Three mistakes to watch for.

  • Defining inside another function. Put 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.
  • Forgetting the parentheses. drawRobot; without () just mentions the function and runs nothing. No error, no robot.
  • Defining but never calling. A definition alone does nothing. If your function “isn’t working”, first check that something actually calls it. A print("drawRobot ran") inside the body will tell you (Week 2).
04Parameters

Parameters: give the function something to work with

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:

parameter
the variable named in the function definition, waiting for a value
argument
the actual value you pass to the function when you call it

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);
}
parameters — names in the definition function functionToDrawBlueSquare(ax, ay, aw) { functionToDrawBlueSquare(100, 100, 50); arguments — values in the call matched by position: 1st → 1st …
When the call runs, each parameter is created as a variable holding its argument: ax = 100, ay = 100, aw = 50. The second call starts fresh with ax = 200, ay = 200, aw = 74.
  • Order is everything. Arguments are matched to parameters by position, not by name. Swap two arguments and you swap their meanings.
  • Parameters are local variables. They exist only inside the function’s braces and disappear when it ends, exactly like the local variables from Week 2’s Scope section.
  • Arguments can be any expression. 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.

05Anchor & offsets

A robot that can go anywhere

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
}

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.

06Return values

Functions that hand back an answer

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
}
let mySum = myFunctionToAddThreeNumbers(12, 8, 10); inside: return 12 + 8 + 10; let mySum = 30; mySum now holds 30 p1 = 12, p2 = 8, p3 = 10 the whole call is replaced by its return value = stores the right side in the left (Week 2)
A call to a function that returns something is an expression: it becomes a value, just like 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
KindWhat it doesExampleCalled as
Does somethingdraws, prints, changes a variabledrawRobot(40, 100, c)a complete statement
Returns somethingworks out a value and hands it backdouble(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.

07Translate

translate(): move the origin, not the shapes

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.

old (0,0) translate(150, 100) new (0,0) translate(150, 100); rect(0, 0, 60, 40); The code says (0, 0), but the rectangle appears at (150, 100) on the canvas, because the origin moved first. Dashed: where it would have been without the translate.
Think of the canvas as a sheet of graph paper and translate() as sliding the paper under your pen. Your pen still draws at the same numbers; the paper moved.

Two rules from the review

  • Translates add up. If you have more than one 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).
  • Everything resets each frame. When 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.

The robot, cleaned up

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().

08Rotate & scale

rotate() and scale() turn and resize the grid

rotate(angle)

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
pivot: (0, 0) pivot: its center rotate(PI / 6); swings around the canvas corner translate(cx, cy); rotate(PI / 6); spins in place
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(amount) or scale(scaleX, scaleY)

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.

  • A negative scale flips that axis. 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 grows everything, including line thickness. After scale(3), a 1-pixel stroke is drawn 3 pixels thick.
  • Scale works from (0,0) too. Shapes move toward or away from the origin as they shrink or grow, which is another reason to translate first.
09Push & pop

push() and pop(): save and restore

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

The finished drawRobot()

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();
}

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.

10Many robots

Functions + loops: one robot becomes a crowd

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);
  }
}

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.

Go further: robots that move

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().

11Reference

Quick reference

Vocabulary

WordMeansExample
definitioncreates the function and its bodyfunction drawRobot() { … }
callruns the functiondrawRobot();
parametera variable named in the definitionx in drawRobot(x, y)
argumenta value passed in the call40 in drawRobot(40, 100)
return valuethe value a function hands backreturn n * 2;
transformationa change to the coordinate gridtranslate(), rotate(), scale()

Function syntax

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

Transformations

FunctionDoesNote
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 everything1 = normal, 2 = double, 0.5 = half
scale(sx, sy)scales x and y separatelynegative flips that axis
push()saves transformations and stylesalways pair with pop()
pop()restores what push() saved 
angleMode(DEGREES)switches angles to degreesput it in setup()
PI, HALF_PI, TWO_PI180°, 90°, 360° in radiansbuilt-in constants

All transformations reset when draw() ends.

12Practice

Be able to do

Parameter or argument?

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.

Make your own character

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?

Give it a position

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?

Predict the return value

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).

Rebuild with translate, scale, push and pop

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.

A crowd

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.

Spin one in place

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.