Reference · Advanced

The canvas element

Use canvas for script-drawn bitmap graphics only when its fallback content, interaction model, scaling, and accessibility are deliberately handled.

Published
Last checked

Definition

canvas provides a scriptable bitmap drawing surface. JavaScript obtains a rendering context and paints pixels. The painted output is not ordinary DOM content, so authors remain responsible for fallback information, controls, focus, hit testing, and high-density rendering.

Minimal syntax

<canvas width="640" height="360">
  A line chart showing a steady increase from 20 to 45 registrations.
</canvas>

The width and height attributes define the drawing buffer. CSS dimensions only scale that buffer and can make the result blurry or distorted when their aspect ratio differs.

Choose canvas deliberately

Canvas suits dense, frequently redrawn pixels such as games or specialized data visualization. Use HTML for text and controls, SVG for inspectable vector shapes, and an image for a fixed graphic. If users need to select, search, translate, or adapt the content, ordinary document elements are usually the stronger base.

Browser and accessibility behavior

Canvas descendants are fallback content, not automatically synchronized with the pixels. Interactive canvas applications need a parallel accessible model and DOM controls whose state matches the drawing. Pointer coordinates must be mapped across CSS size, drawing-buffer size, zoom, and device pixel ratio.

Common failures

  • Text and controls exist only as pixels.
  • CSS stretches a low-resolution drawing buffer.
  • A chart has a generic fallback sentence but omits its actual data or finding.
  • Keyboard focus has no visible equivalent inside the drawn interface.

Verification checklist

Disable scripts and inspect the fallback. At high pixel density and zoom, confirm the drawing stays sharp and pointer targets align. Complete every task without a pointer and inspect the accessibility tree for names, roles, states, and order. For data graphics, provide a nearby table or equivalent description and verify it stays synchronized whenever the canvas changes.

Test printing, forced colours, and a failed drawing context when those modes matter to the task. Record which information is available outside the pixels; an attractive bitmap is not an equivalent when its values, labels, or controls cannot be reached programmatically.