p5.js Session 9: Functions

Stop repeating yourself: name a block of code once with a function, then call it as often as you like.

Last session ended with four nearly identical blocks of code, one per flower, differing only in two numbers. Functions are how we stop writing that twelve times over.

Naming a block of code

A function is a block of code with a name. You write it once, then call that name whenever you want it to run.

function setup() {
  createCanvas(600, 600);
  angleMode(DEGREES);
  noLoop();
  noStroke();
}

function draw() {
  background(0);
  drawFlower();
}

function drawFlower() {
  push();
  translate(300, 300);
  for (let i = 0; i < 8; i++) {
    rotate(45);
    fill(0, 0, 255);
    ellipse(60, 0, 90, 35);
  }
  fill(255, 0, 0);
  circle(0, 0, 25);
  pop();
}

A single flower drawn by calling the drawFlower() function once

drawFlower() is the whole push()/pop() block from last session, just given a name. draw() doesn’t need to know what’s inside it, it just calls drawFlower() and trusts it to handle the rest.

Parameters

Right now drawFlower() always draws in the same spot, (300, 300), because that’s hardcoded inside it. Parameters let us pass a value in each time we call the function, so it can behave differently on demand.

function setup() {
  createCanvas(600, 600);
  angleMode(DEGREES);
  noLoop();
  noStroke();
}

function draw() {
  background(0);
  drawFlower(150, 150);
  drawFlower(450, 150);
  drawFlower(150, 450);
  drawFlower(450, 450);
}

function drawFlower(x, y) {
  push();
  translate(x, y);
  for (let i = 0; i < 8; i++) {
    rotate(45);
    fill(0, 0, 255);
    ellipse(60, 0, 90, 35);
  }
  fill(255, 0, 0);
  circle(0, 0, 25);
  pop();
}

Four flowers, one in each corner, produced by calling drawFlower() four times with different x and y values

Same four-corner result as last session, but now it’s one function and four short calls instead of four copies of the same dozen lines. If we ever want to change how the flower looks, petal colour, count, size, we change it in one place and every call updates.


In Session 10 we let random() decide where, and how many times, drawFlower() gets called.