← Docs
Recipe

Canvas 2D Primer

Every pixel is a decision. The 2D context is your first graphics API — master it before touching a GPU.

The Grid

A <canvas> element is a raster of RGBA pixels. Its coordinate origin is top-left. Width and height attributes set the backing store size — CSS width/height only scales the element.

Acquiring Context

const c = document.getElementById('c') as HTMLCanvasElement;
const ctx = c.getContext('2d')!;

The CanvasRenderingContext2D is a state machine. Every draw call reads the current fillStyle, strokeStyle, lineWidth, and transform.

Immediate Mode

Canvas draws immediately — no retained scene graph. Once pixels hit the backing store, the shape is gone. To animate, clear and redraw every frame with requestAnimationFrame.

Path API

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 80);
ctx.lineTo(100, 140);
ctx.closePath();
ctx.fillStyle = '#8B5CF6';
ctx.fill();
ctx.strokeStyle = '#F472B6';
ctx.stroke();

beginPath resets the subpath list. closePath draws a segment back to the last moveTo. Fill and stroke are independent — you can do both on the same path.

Transform Stack

ctx.save() pushes the entire state — transform, styles, clipping region — onto a stack. ctx.restore() pops it. Use this to isolate coordinate system changes.

Pixel Manipulation

getImageData returns a flat Uint8ClampedArray of RGBA values. Modify it directly, then write back with putImageData. This is the bridge to software rendering.