Docs β€Ί Transforms

πŸ”„ Transforms

Move and rotate the canvas to draw things at angles or offset positions. Always use push() and pop() to save and restore your position!

push

Saves the current drawing state (colors, stroke, transforms) onto a stack. Use with pop() to temporarily change settings without affecting later drawing.

Tip: Always pair push() with pop()! Think of it like opening and closing parentheses.
function setup() {
  size(400, 300);
}

function draw() {
  background("white");

  fill("dodgerblue");
  rect(10, 10, 50, 50);

  push();
  fill("tomato");
  translate(200, 150);
  rotate(45);
  rect(-25, -25, 50, 50);
  pop();

  rect(340, 240, 50, 50);
}

pop

Restores the drawing state that was saved by the last push(). Any changes to fill, stroke, translate, or rotate since push() are undone.

Tip: After pop(), your fill and stroke go back to whatever they were before the matching push().
function setup() {
  size(400, 300);
}

function draw() {
  background("white");

  fill("dodgerblue");
  circle(100, 150, 40);

  push();
  fill("tomato");
  noStroke();
  circle(200, 150, 40);
  pop();

  circle(300, 150, 40);
}

translate(x, y)

Moves the origin point (0, 0) to a new position. After translate(100, 50), drawing at (0, 0) actually draws at (100, 50). Use with push/pop!

ParameterTypeDescription
xnumberHow far to shift right
ynumberHow far to shift down
Tip: translate is especially useful with rotate β€” translate to the center of a shape, rotate, then draw the shape centered at (0, 0).
function setup() {
  size(400, 300);
}

function draw() {
  background("white");
  noStroke();

  for (let i = 0; i < 5; i++) {
    push();
    translate(40 + i * 80, 150);
    fill("hsl(" + (i * 60) + ", 80%, 60%)");
    rect(-20, -20, 40, 40);
    pop();
  }
}

rotate(angle)

Rotates everything you draw after this call. The angle is in degrees. Rotation happens around the current origin β€” use translate() first to rotate around a specific point.

ParameterTypeDescription
anglenumberRotation angle in degrees
Tip: To spin a shape in place: push(), translate to the center, rotate, draw centered at (0,0), pop().
function setup() {
  size(400, 300);
}

function draw() {
  background("white");

  push();
  translate(200, 150);
  rotate(frameCount);
  fill("tomato");
  rect(-40, -40, 80, 80);
  pop();

  fill("black");
  textSize(14);
  text("Spinning!", 170, 260);
}