Code

Canvas

Transformations

Intermediatetranslate, rotate, scale, setTransform, and the save/restore state stack. MDN Reference

// Translate — move origin
ctx.save();
ctx.translate(100, 70); // new (0,0)
ctx.fillRect(-50, -30, 100, 60);
ctx.restore();

// Rotate around a point
ctx.save();
ctx.translate(280, 70);  // pivot
ctx.rotate(Math.PI / 6); // 30°
ctx.fillRect(-50, -30, 100, 60);
ctx.restore();

// Scale
ctx.save();
ctx.translate(440, 70);
ctx.scale(1.6, 0.7); // wider, shorter
ctx.fillRect(-50, -30, 100, 60);
ctx.restore();

// setTransform — full matrix (skew)
// setTransform(a, b, c, d, e, f)
// ┌ a  c  e ┐   ┌ scaleX  skewX  tx ┐
// │ b  d  f │ = │ skewY   scaleY ty │
// └ 0  0  1 ┘   └ 0       0      1  ┘
ctx.save();
ctx.setTransform(1, 0.4, 0, 1, 300, 195);
ctx.fillRect(-50, -30, 100, 60);
ctx.restore();

// Save/restore stack — nested transforms
const drawNested = (depth: number) => {
  if (depth === 0) return;
  ctx.save();
  ctx.rotate(Math.PI / 8);
  ctx.strokeRect(-40 + depth*3, -20 + depth*3,
                  80 - depth*6,  40 - depth*6);
  drawNested(depth - 1);
  ctx.restore();
};
Key APIs
  • ctx.save() / ctx.restore() — push/pop the entire canvas state
  • ctx.translate(x, y) — shift the coordinate origin
  • ctx.rotate(radians) — rotate around the current origin
  • ctx.scale(sx, sy) — stretch/shrink (negative = flip)
  • ctx.setTransform(a,b,c,d,e,f) — set the full 2D transform matrix directly
  • ctx.resetTransform() — restore identity matrix without affecting state stack