Skip to content

Lesson 3 of 9 · 25m

Canvas Is Immediate Mode: Pixels, State, and Redraws

Build the correct mental model for canvas as a stateful bitmap API, including backing scale, paths, transforms, compositing, and the absence of scene memory.

Canvas looks simple in the first tutorial and strange in production because it remembers almost nothing. You issue drawing commands, pixels change, and the browser forgets what those pixels meant. There is no circle object, hit target, text node, or automatic invalidation. If something moves, you redraw the world.

The canvas is a bitmap with a transform

const ctx = document.querySelector('#plot').getContext('2d')
ctx.fillStyle = '#172033'
ctx.fillRect(0, 0, 640, 360)
ctx.beginPath()
ctx.moveTo(20, 300); ctx.lineTo(220, 90)
ctx.stroke()

The width and height attributes define backing-store pixels. CSS width and height define display size. Confusing those two is the classic cause of blurry canvas.

Context state is a stack

ctx.save()
ctx.translate(x, y)
ctx.rotate(angle)
ctx.fillRect(-12, -12, 24, 24)
ctx.restore()

The context carries styles, transforms, alpha, composite operation, shadows, font, and clipping. Omit restore() and that state leaks into unrelated drawing.

Paths are built, then consumed

ctx.beginPath()
ctx.arc(80, 80, 30, 0, Math.PI * 2)
ctx.fill(); ctx.stroke()

A path is not a retained shape object. beginPath() discards prior geometry; fill() and stroke() paint what is currently accumulated. Forget beginPath() in a loop and old geometry is painted again.

Redraw means redraw

function render(scene) {
  ctx.setTransform(deviceScale, 0, 0, deviceScale, 0, 0)
  ctx.clearRect(0, 0, width, height)
  drawEntities(ctx, scene.entities)
}

Clearing everything feels wasteful if you come from the DOM, but for dynamic scenes it is often cheaper than tracking dirty regions. Optimization means doing less work, not preserving object identity that canvas never had.

Compositing and semantics are your problem

globalCompositeOperation = 'lighter' is useful for glows because new pixels add to existing pixels. It is also order-dependent: alpha, shadows, transparent fills, and draw order change the result. After painting a blue rectangle and the word Export, the browser does not know a button exists. You must implement hit testing, focus, keyboard interaction, and semantics separately — or put real HTML over the canvas. Canvas is for pixels; the DOM is still your accessibility layer.

Field notes

  • Assigning canvas.width resets the bitmap and context state even if the value is unchanged.
  • getContext('2d') returns the same context each time; it does not create layers.
  • Large shadows expand rasterization cost; pre-render repeated glows into sprites.
  • If every object needs keyboard focus and semantic identity, canvas is the wrong abstraction.

Was this lesson helpful?

Sign in to rate