p5.js Session 7: Translate and Rotate

Move the canvas origin and spin your shapes around it to build a flower from rotated petals.

Grids gave us control over position. This session is about control over orientation: moving where you draw from, then turning what you draw.

Moving the origin with translate()

let cx;
let cy;

function setup() {
  createCanvas(600, 600);
  noLoop();
  stroke(255, 255, 255);

  cx = width / 2;
  cy = height / 2;
}

function draw() {
  background(0);
  translate(cx, cy);
  ellipse(0, 0, 150, 150);
}

Circle outline drawn at the canvas centre using translate()

Rotating around the origin

let cx;
let cy;

function setup() {
  createCanvas(600, 600);
  angleMode(DEGREES);
  noLoop();
  stroke(255, 255, 255);
  cx = width / 2;
  cy = height / 2;
}

function draw() {
  background(0);
  translate(cx, cy);
  circle(0, 0, 15);
  for (let i = 0; i < 8; i++) {
    rotate(45);
    fill(255, 255, 255);
    rect(100, 0, 60, 60);
    fill(255, 0, 0);
    circle(100, 0, 15);
  }
}

Eight white squares arranged in a ring around the canvas centre, each marked with a red anchor point, rotated using rotate() inside a for loop

We’ve already got everything we need: a centre point, a loop, and a rotation. From here it’s just a matter of swapping the shapes for something that reads as petals instead of squares.

Building the flower

let cx;
let cy;

function setup() {
  createCanvas(600, 600);
  angleMode(DEGREES);
  noLoop();
  noStroke();
  cx = width / 2;
  cy = height / 2;
}

function draw() {
  background(0);
  translate(cx, cy);
  for (let i = 0; i < 8; i++) {
    rotate(45);
    fill(0, 0, 255);
    ellipse(130, 0, 200, 75);
  }
  fill(255, 0, 0);
  circle(0, 0, 60);
}

Same loop and rotation as before, but the squares are gone. Each turn of the loop draws a wide, flattened blue ellipse offset from the centre, which reads as a petal once there are eight of them overlapping around a point. The red circle goes last, sitting on top in the middle as the flower’s core.

Finished flower sketch: eight blue ellipse petals rotated around a centre, with a red circle at the middle


In Session 8 we look at push() and pop(): saving and restoring the canvas position.