HTML Canvas: Paths, Pixels, and requestAnimationFrame
A canvas element is a drawable raster surface controlled entirely by script. Unlike the DOM, where every rectangle is an object you can select, style, and inspect, canvas paints pixels immediately and forgets. That single design decision is why canvas powers charts, games, drawing tools, and data visualizations at frame rates the DOM cannot match â and why the same feature feels hostile the moment you need crisp text on a retina display or a click target that lines up with what the user sees.
This lesson builds a mental model of the immediate-mode pipeline, then walks through the four problems every real canvas project hits: device pixel ratio, coordinate mapping, animation timing, and input. The result is a small but production-shaped drawing module you can reuse.
Immediate Mode Means You Own Every Frame
The 2D context exposes a state machine: a current fill style, stroke style, line width, transform, and clip region. Drawing a rectangle commits pixels to the bitmap right away. There is no retained shape object to mutate later. If you need a circle to move, you clear the region and draw the circle again somewhere else â every frame, for as long as the animation runs.
That model has two consequences. First, performance is predictable: cost scales with pixels painted, not with the number of objects in a scene. Second, features the DOM gives you free â hit testing, responsive reflow, accessibility â become your responsibility. Plan for them before the codebase grows.
Device Pixel Ratio: Why Everything Looks Blurry
A canvas declared with width of eight hundred and a CSS width of eight hundred logical pixels has a one-to-one backing store. On a display with a device pixel ratio of two, the browser stretches that bitmap across sixteen hundred physical pixels, and every edge softens. The fix is to multiply the backing store by the ratio and scale the context to match:
function fitCanvas(canvas, cssWidth, cssHeight) {
const dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(cssWidth * dpr);
canvas.height = Math.round(cssHeight * dpr);
canvas.style.width = cssWidth + 'px';
canvas.style.height = cssHeight + 'px';
const ctx = canvas.getContext('2d');
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
return ctx;
}
const canvas = document.getElementById('chart');
const ctx = fitCanvas(canvas, 640, 320);
ctx.fillStyle = '#0f172a';
ctx.fillRect(0, 0, 640, 320);
After this setup every coordinate you pass is in CSS pixels â the same units your layout uses â while the bitmap still has enough physical pixels to stay sharp. Re-run the fit on window resize, and clear the canvas before redrawing, because changing width or height resets the entire bitmap and context state.
| Pitfall | Symptom | Fix |
|---|---|---|
| Backing store ignores DPR | Blurry lines and text on retina | Multiply width and height by devicePixelRatio |
| CSS size not set | Canvas renders at physical size, layout jumps | Set style width and height in CSS pixels |
| Forgetting to clear | Ghost trails behind moving shapes | Clear the full logical rectangle each frame |
| Forgetting to reset transform | Coordinates drift after re-fit | Call setTransform after every resize |
Paths, Strokes, and Fills
Everything beyond rectangles goes through the path API. Begin a path, move the pen, add lines or arcs, then either stroke the outline or fill the interior â or both. The path persists until the next beginPath call, which is what lets one contour be both stroked and filled without drawing it twice by hand:
function roundBar(ctx, x, y, w, h, radius, fill, stroke) {
const r = Math.min(radius, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
if (fill) { ctx.fillStyle = fill; ctx.fill(); }
if (stroke) { ctx.strokeStyle = stroke; ctx.lineWidth = 1.5; ctx.stroke(); }
}
roundBar(ctx, 24, 24, 200, 48, 10, '#38bdf8', '#0369a1');
Two details separate clean canvas code from jagged output. Coordinates on half-pixel boundaries produce anti-aliased blur on one-pixel lines; offset crisp strokes by half a pixel or snap coordinates with Math.round. And ctx.save plus ctx.restore bracket any temporary style change so one component cannot leak its fill style into the next.
Animating with requestAnimationFrame
Never drive canvas animation with setInterval. The browser batches rAF callbacks with its own paint cycle, skips them in background tabs, and hands you a timestamp you can use to compute delta time â the only reliable way to keep motion speed independent of frame rate:
let last = 0;
let ballX = 40;
function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
ctx.clearRect(0, 0, 640, 320);
ballX += 180 * dt;
if (ballX > 640) ballX = 40;
ctx.beginPath();
ctx.arc(ballX, 160, 18, 0, Math.PI * 2);
ctx.fillStyle = '#f59e0b';
ctx.fill();
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
The clamp on dt matters: a stalled tab resumes with a huge timestamp gap, and without the cap the ball teleports across the screen. For physics-style motion, integrate position from velocity times dt rather than adding a fixed step per frame.
Mapping Pointer Coordinates Back to Drawing Space
Mouse and touch events report client coordinates in the viewport, not canvas space. Subtract the element's bounding rectangle, then divide by the CSS-to-canvas scale if you resized the surface with a transform:
function canvasPoint(canvas, clientX, clientY) {
const rect = canvas.getBoundingClientRect();
return {
x: (clientX - rect.left) * (canvas.width / rect.width),
y: (clientY - rect.top) * (canvas.height / rect.height)
};
}
canvas.addEventListener('pointerdown', (event) => {
const { x, y } = canvasPoint(canvas, event.clientX, event.clientY);
ctx.beginPath();
ctx.arc(x, y, 6, 0, Math.PI * 2);
ctx.fillStyle = '#22c55e';
ctx.fill();
});
Prefer pointer events over separate mouse and touch handlers: one code path covers pen, mouse, and finger, and pointer capture keeps the stroke alive when the pointer leaves the element mid-drag. When the context transform is already scaled by the device pixel ratio, work in CSS pixels as shown; the canvasPoint helper above handles the raw backing-store mapping for the unscaled case, so pick one convention and stay with it.
Gradients, Text, and Clipped Effects
Beyond flat fills, the context offers linear and radial gradients, patterns, dashed strokes, and a clip region that constrains all later drawing. Gradients are defined in coordinate space and then assigned to fillStyle or strokeStyle like any color:
const gradient = ctx.createLinearGradient(0, 320, 0, 40);
gradient.addColorStop(0, '#38bdf8');
gradient.addColorStop(1, '#6366f1');
ctx.fillStyle = gradient;
ctx.fillRect(0, 40, 640, 280);
ctx.save();
ctx.beginPath();
ctx.rect(0, 40, 320, 280);
ctx.clip();
ctx.fillStyle = 'rgba(255,255,255,0.25)';
ctx.beginPath();
ctx.arc(320, 180, 120, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
The clip is confined by save and restore, so the translucent highlight never bleeds past the left half. Text on canvas needs explicit font shorthand and benefits from the same half-pixel care as lines: set ctx.font, choose fillStyle, then use fillText at a baseline coordinate â remember that the y position is the text baseline, not the top of the box. measureText returns width for centering or truncation logic. For data labels at small sizes, render at the device pixel ratio as configured earlier; text is where blurry canvas output is most obvious.
When Canvas Is the Wrong Tool
If the graphic must respond to search, screen readers, or CSS hover, canvas is the wrong substrate â those concerns need real DOM nodes. SVG keeps shapes as inspectable elements with native focus and styling, at the cost of performance when the shape count runs into the thousands. A practical split: SVG or DOM for interface chrome, canvas for dense or animated content, and an accessible DOM summary (a table of values, a text description) alongside every data visualization rendered on canvas.
| Need | Prefer |
|---|---|
| Fewer than a few hundred interactive shapes | SVG or DOM |
| Particle systems, games, dense charts | Canvas |
| CSS hover, focus rings, screen readers | DOM or SVG |
| Export to PNG at arbitrary resolution | Canvas |
| Print-quality vector output | SVG |
Design the redraw loop so the scene can be rebuilt from state at any moment. That habit makes resize handling, undo in a drawing app, and theme changes a matter of mutating state and scheduling one more frame, rather than hunting through imperative draw calls for the one rectangle that was missed.
âĄBatch by state, not by shape
Changing fillStyle or line width between every path forces style flushes. Group all fills, then all strokes, or sort shapes by style before the draw pass â the context rewards batching the same way a render pipeline does.
Common Mistakes
Drawing at the CSS pixel resolution and stretching the bitmap
Fix: Multiply the backing store by devicePixelRatio and scale the context with setTransform.
Animating with setInterval and a fixed step per tick
Fix: Use requestAnimationFrame and delta time so motion is smooth and frame-rate independent.
Using clientX and clientY directly as canvas coordinates
Fix: Subtract getBoundingClientRect offsets and map into canvas space before drawing.
Never clearing between frames, producing trails
Fix: Clear the full logical area at the top of every frame, then redraw the scene.
Canvas-only data visualizations with no text alternative
Fix: Ship an accessible table or summary next to the drawing for screen-reader users.
Key Takeaways
- Canvas is immediate mode: pixels are committed now, so every animated frame must clear and redraw.
- Device pixel ratio explains the universal blur problem; fix it by scaling the backing store and the context together.
- Paths are built once per contour and then stroked, filled, or both â save and restore around style changes.
- requestAnimationFrame with clamped delta time is the only sane animation clock.
- Pointer events plus a coordinate-mapping helper keep input aligned with what the user sees.
- Choose canvas for density and motion; keep DOM and SVG for anything that needs semantics or styling hooks.