Lesson 4 of 9 · 28m
Canvas Performance: Batch Work and Respect the Rasterizer
Diagnose real canvas bottlenecks, cap backing-store cost, batch state changes, layer expensive content, manage images, and measure before optimizing.
Canvas performance advice is full of superstition because people measure the wrong thing. They count draw calls while a phone rasterizes a 4,000-pixel backing store, or optimize paths while drawImage decodes a huge PNG every frame. Treat canvas as a pipeline: CPU command generation, rasterization, image decode, texture upload, compositing, and memory bandwidth.
Measure the frame, not the vibe
function frame(now) {
const dt = now - last; last = now
update(dt); render(); requestAnimationFrame(frame)
}A 60 Hz frame budget is 16.7 ms total, not 16.7 ms for drawing. Input, layout, paint, and compositing share that time. On mobile, assume script has closer to 5-8 ms until measurement proves otherwise.
The backing store is a performance decision
const dpr = Math.min(window.devicePixelRatio || 1, 2)
canvas.width = Math.round(canvas.clientWidth * dpr); canvas.height = Math.round(canvas.clientHeight * dpr)
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)A DPR of 3 means nine times as many backing pixels as CSS pixels. Cap DPR for heavy visualizations. A slightly softer DPR-2 frame is better than a beautiful frame that arrives late.
Batch compatible drawing state
for (const [color, group] of groups) {
ctx.fillStyle = color
ctx.beginPath()
for (const item of group) ctx.arc(item.x, item.y, item.r, 0, Math.PI * 2)
ctx.fill()
}Grouping reduces style churn and lets one fill paint many subpaths. Remember that overlap behavior can change when separate fills become one path; batching is a rendering decision, not a mechanical rewrite.
Layer content by update rate
<div class="stage">
<canvas id="grid"></canvas>
<canvas id="data"></canvas>
<canvas id="overlay"></canvas>
</div>Render the grid after resize, data when data changes, and overlay during pointer movement. Two to four meaningful layers is usually enough; dozens of canvases create memory and compositing overhead.
Images and allocation hide cost
drawImage can trigger decoding, scaling, color conversion, and texture upload. Preload with await image.decode() and pre-scale assets. For repeated complex markers or shadows, render once into an offscreen canvas and stamp it.
Avoid reading layout properties or allocating arrays, closures, and objects in hot loops. Reusing scratch arrays is boring, effective engineering.
Field notes
willReadFrequently: truehelps contexts repeatedly usinggetImageData, but can hurt normal GPU-accelerated rendering.- Resizing any canvas clears it. Resize handlers must redraw every layer.
- Text is expensive. Cache static labels or render them in DOM overlays.
- OffscreenCanvas can move rendering to a worker, but it is an architectural migration, not a one-line fix.
Was this lesson helpful?