Skip to content

Canvas or the DOM

Canvas is a bitmap you paint and repaint yourself; the DOM keeps each element as a node the browser styles, lays out, paints and exposes to assistive tools. The choice decides how much of that work you take on.

On this page

What it is

The DOM is the browser's in-memory tree of the document, with a node for each element, and both HTML and SVG documents are modeled this way. You describe what should be on screen; the browser combines that tree with the CSS to compute each node's style, runs layout to find its size and position, paints each box to pixels, and builds an accessibility tree from it for assistive technology. A click fires on the innermost element under the pointer and bubbles up through its ancestors, so the element itself is the event target. A canvas is a different kind of thing: a bitmap that JavaScript draws into through the Canvas API, which MDN describes as a tool for animation, game graphics, data visualization, photo manipulation and live video. Once a shape is painted, the browser holds pixels and no record of the shape, so it doesn't know what's under the pointer and has nothing to read to a screen reader.

A useful way to hold the difference: with the DOM you edit a tree the browser retains (its methods change structure, style or content) and the browser reflows and repaints the affected part; with canvas you issue drawing commands and retain the scene yourself, in your own data structures, then redraw when it changes. That is why a canvas app grows a model of "what is where" that a DOM app gets from the tree. Hit testing becomes geometry against that model, hover and selection become fields in it, and the redraw loop reads it on each frame. Schedule those redraws with requestAnimationFrame rather than setInterval.

Two more costs show up on the first real screen. On a high-resolution display a canvas sized in CSS pixels is upscaled by devicePixelRatio and looks soft; the fix is to multiply the width and height attributes by the ratio, scale the drawing context by the same factor, and keep the CSS size as it was. And text on a canvas is a picture of letters: it blurs under screen magnification and is invisible to a screen reader.

ts
const canvas = document.querySelector('canvas')!;
const ctx = canvas.getContext('2d', { alpha: false })!;

// 1. Size the bitmap for the screen, not just the CSS box
const dpr = window.devicePixelRatio;
const rect = canvas.getBoundingClientRect();
canvas.width = Math.round(rect.width * dpr);
canvas.height = Math.round(rect.height * dpr);
ctx.scale(dpr, dpr);

// 2. Your own scene model: the browser keeps no record of shapes
type Point = { x: number; y: number; r: number; label: string };
const points: Point[] = loadPoints();
let dirty = true;

function frame() {
  if (dirty) {
    ctx.clearRect(0, 0, rect.width, rect.height);
    for (const p of points) {
      ctx.beginPath();
      ctx.arc(Math.floor(p.x), Math.floor(p.y), p.r, 0, Math.PI * 2);
      ctx.fill();
    }
    dirty = false;
  }
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

// 3. Hit testing is yours too; the tooltip stays in the DOM
canvas.addEventListener('pointermove', (e) => {
  const hit = points.find((p) => Math.hypot(p.x - e.offsetX, p.y - e.offsetY) <= p.r);
  showTooltip(hit ? hit.label : null, e.clientX, e.clientY);
});

When to use it

Reach for canvas when the number of marks, or how often they change, is the problem. A DOM pays roughly per element: the browser computes styles for the nodes in the render tree, lays them out and paints them, and a change that moves content triggers a reflow and repaint of the affected part. A 2D canvas frame costs roughly what you paint in it, so our rule of thumb is that a dense scatter plot or a fast-scrolling grid belongs on canvas once you can paint the visible part and little else. Games, dense data visualization and live video all share that shape: the picture is dense or changes constantly.

Reach for it when the task is the pixels themselves: filters on an uploaded photo, drawing on top of video frames, a custom rendering style you would otherwise fake with layered elements. Photo manipulation and real-time video processing are among the documented uses of the Canvas API.

When drawing itself starts to stall input, move it off the main thread. OffscreenCanvas decouples rendering from the document so it can run inside a worker; transferControlToOffscreen() hands an on-screen canvas to a worker, which draws into it while the main thread keeps handling events. This is a second step, after the drawing is already on canvas and still too slow.

Once you are on canvas, the documented performance habits are worth naming in a design round: pre-render repeated shapes to an offscreen canvas and copy them in, split static and moving content across layered canvases, put a static background in CSS under the canvas instead of repainting it, round coordinates to integers to avoid sub-pixel anti-aliasing, pass alpha: false when the canvas needs no transparency, batch drawing calls, and redraw the changed region rather than the whole scene.

When not to

Stay in the DOM for anything that is mostly text or controls: forms, lists, menus, tables of ordinary content, prose. The browser builds its accessibility tree from those elements, moves keyboard focus through the interactive ones (links and form controls by default, others with tabindex), and keeps text as text, which stays legible when magnified. Painted onto a canvas, the same content becomes pixels the browser holds no information about. MDN's guidance is direct: use canvases the way you use images, and avoid them for significant text or interactive content.

Stay in the DOM when the count is large but the content is rows. Our advice for a long list or table of ordinary content is to look at list virtualization before leaving the DOM, so the content stays as elements and the browser keeps doing the work above. Canvas is for when the cells themselves are graphics, or the grid must repaint faster than a DOM approach allows.

Don't build one giant canvas for a document-sized surface. The maximum canvas size depends on the browser and device; MDN notes that most allow more than 10,000 by 10,000 pixels while iOS devices stop at 4,096 by 4,096, and a canvas past the limit stops drawing altogether. Size the canvas to the viewport and translate your model as the user scrolls or zooms.

Compared

OptionWho keeps the sceneReach for it whenPick something else when

DOM (HTML, CSS, SVG elements)

The browser: style, layout, paint, event delivery and the accessibility tree come with the elements; controls can take focus

Text, controls, forms, moderate numbers of interactive shapes

The scene is dense and repaints constantly, or you need to touch pixels

Canvas 2D

Your code: a bitmap plus your own scene model and hit testing

Dense charts, games, image and video processing, a drawing surface

The content is mostly text, or must stay legible under magnification and readable by assistive tools

WebGL on a canvas

Your code, with the GPU doing the drawing

3D, or a 2D scene the 2D context fails to keep at frame rate

The 2D context already meets the budget; shaders cost more to write and debug

OffscreenCanvas in a worker

Your code, off the main thread

Drawing work itself stalls input or animation

Drawing is cheap; the extra messaging buys nothing

Hybrid: canvas plus DOM overlay

Canvas for the picture; DOM for inputs, tooltips, menus and fallback content

The canvas needs text input, menus or tooltips

The overlay would hold most of the interface anyway, so it is a DOM app

In a picture

DataScene model

Step 1 of 3

Keep your own model

Data comes in and goes into a scene model: positions, sizes, labels, hover and selection state. On a canvas this model is the record of what is where, because the browser keeps none.

How to say it in an interview

The common mistake

Quiz

A chart has 200 points, each needs a tooltip, keyboard focus and a label for screen readers. Which fits better, and why?
A canvas chart looks soft on a high-resolution laptop but fine on an older monitor. What is happening?
You moved a large data grid from table elements to a canvas, and screen reader users now hear nothing. What is the fix?
A canvas animation drops frames. The background is a static image repainted each tick, and shapes are drawn at fractional coordinates. What do you change first?

Related

Sources

  1. MDN: Canvas API
  2. MDN: The canvas element
  3. MDN: Optimizing canvas
  4. MDN: OffscreenCanvas
  5. web.dev: High DPI canvas
  6. MDN: Document Object Model (DOM)
  7. MDN: Populating the page: how browsers work
  8. MDN: Event bubbling
  9. MDN: Keyboard-navigable JavaScript widgets
Sign in to report a mistake