All posts

rotate

1 post

p5.js Session 7: Translate and Rotate

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);
}
  • cx and cy store the centre point of the canvas, calculated once in setup() so we don’t repeat width / 2 and height / 2 every time we need them.
  • translate(cx, cy) moves the origin there, so ellipse(0, 0, 150, 150) lands dead centre instead of in the top-left corner.

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);
  }
}
  • angleMode(DEGREES) tells p5.js to read angles in degrees rather than radians.
  • rotate(45) turns the canvas a little further each time round, eight times in total, adding up to a full 360-degree turn.
  • Each square is drawn at the same offset point, (100, 0), but lands somewhere new around the centre because the canvas has already been rotated by a different amount.
  • The small red circle marks that anchor point on each square.
  • The white circle at (0, 0) is just a reference dot showing where the origin sits after translate().

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.