The Canvas Element: Drawing, Animation, and When to Choose Canvas over SVG

Canvas vs SVG: how the 2D context works, sharp drawing on high-DPI screens, animation loops, OffscreenCanvas, accessibility, and when to pick each.

Executive Summary: Canvas is a bitmap you paint with JavaScript; SVG is a tree of shapes the browser keeps and redraws for you. Canvas wins when you draw thousands of objects, redraw every frame or manipulate pixels. SVG wins when you need crisp scaling, CSS styling, built-in events on each shape, and accessibility. Most canvas bugs come from three things: forgetting to scale for high-DPI screens, animating with timers instead of requestAnimationFrame, and shipping a picture that screen readers cannot see at all.
Canvas with a filled circle and a line chart drawn by JavaScript

A team builds a dashboard chart in SVG. It looks great with 200 points. A year later the same chart renders 40,000 sensor readings, and scrolling the page stutters because the browser is managing 40,000 DOM nodes. Another team builds a simple bar chart in canvas, and then spends a week adding tooltips, hover states and a way for screen reader users to get the numbers, all of which SVG would have given them almost for free.

The canvas element, <canvas>, is a rectangular bitmap that you draw on with a JavaScript API, most commonly the 2D rendering context. It is immediate mode: once you draw a circle, the canvas only remembers pixels, not that a circle exists. SVG is retained mode: each shape is an element in the DOM that the browser keeps, re-renders on change and can attach events to. That one difference drives every decision below.

How do you draw on a canvas?

<canvas id="chart" width="600" height="300">
  Monthly signups rose from 120 in January to 410 in June.
</canvas>

<script>
  const canvas = document.getElementById("chart");
  const ctx = canvas.getContext("2d");

  ctx.fillStyle = "#2563eb";
  ctx.fillRect(40, 180, 60, 100);       // x, y, width, height

  ctx.beginPath();
  ctx.arc(300, 150, 40, 0, Math.PI * 2);
  ctx.strokeStyle = "#0f172a";
  ctx.lineWidth = 3;
  ctx.stroke();

  ctx.font = "16px system-ui";
  ctx.fillStyle = "#0f172a";
  ctx.fillText("Signups", 40, 30);
</script>

The coordinate system starts at the top-left corner, with y growing downward. Shapes are built from paths (beginPath, moveTo, lineTo, arc, bezierCurveTo) and then filled or stroked. Styles such as fillStyle and lineWidth are state on the context; ctx.save() and ctx.restore() push and pop that state so one drawing routine does not leak styles into the next. The text between the canvas tags is fallback content, discussed in the accessibility section below.

How do you keep a canvas sharp on high-DPI screens?

The width and height attributes set the bitmap’s size in pixels. CSS sets its displayed size. On a phone or a Retina laptop with a device pixel ratio of 2 or 3, a 600-pixel bitmap stretched over 600 CSS pixels looks blurry, because each canvas pixel covers four or nine physical pixels. Scale the bitmap to match:

function setupCanvas(canvas) {
  const dpr = window.devicePixelRatio || 1;
  const rect = canvas.getBoundingClientRect();

  canvas.width = Math.round(rect.width * dpr);
  canvas.height = Math.round(rect.height * dpr);

  const ctx = canvas.getContext("2d");
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);   // draw in CSS pixels from now on
  return ctx;
}

const ctx = setupCanvas(document.getElementById("chart"));

Size the canvas with CSS (for example width: 100%; height: 300px), then call the setup function. Setting width or height clears the canvas and resets the context state, so redraw after every resize. A ResizeObserver on the canvas is the cleanest trigger, since it fires when the element’s size changes for any reason, not just window resizes.

How do you animate a canvas?

Canvas animation is a loop: clear, update, draw, repeat. Run it with requestAnimationFrame, never setInterval. The browser calls your function just before the next repaint, matches the display’s refresh rate, and pauses the loop in background tabs to save battery.

const ball = { x: 50, y: 150, vx: 240 };   // vx in pixels per second
let last = performance.now();

function frame(now) {
  const dt = (now - last) / 1000;           // seconds since the previous frame
  last = now;

  ball.x += ball.vx * dt;
  if (ball.x > 560 || ball.x < 40) ball.vx *= -1;

  ctx.clearRect(0, 0, 600, 300);
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, 20, 0, Math.PI * 2);
  ctx.fill();

  requestAnimationFrame(frame);
}

requestAnimationFrame(frame);

Multiply movement by the elapsed time dt, not by a fixed amount per frame. Otherwise the animation runs twice as fast on a 120 Hz display as on a 60 Hz one. Respect prefers-reduced-motion by checking matchMedia("(prefers-reduced-motion: reduce)") and drawing a static frame instead of looping.

If you want a refresher on why long-running JavaScript freezes this loop, I explained the event loop in event loop and callback queue. A frame has about 16 milliseconds on a 60 Hz screen; anything that blocks the main thread longer than that drops frames.

Moving rendering off the main thread

OffscreenCanvas lets you hand a canvas to a Web Worker and draw there, so heavy rendering does not compete with input handling and layout on the main thread. With Safari 16.4 shipping it in March 2023, it now works in all major browsers.

// main.js
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker("render-worker.js");
worker.postMessage({ canvas: offscreen }, [offscreen]);

// render-worker.js
onmessage = ({ data }) => {
  const ctx = data.canvas.getContext("2d");
  // draw and animate here; requestAnimationFrame is available in dedicated workers
};

Interactivity is your job

In SVG, a <circle> can have a click handler, a :hover style and a <title> tooltip. In canvas there are only pixels, so hit testing is manual: listen for pointer events on the canvas, convert the event coordinates to canvas coordinates, and check which of your own objects contains that point.

canvas.addEventListener("pointermove", (e) => {
  const rect = canvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  const hit = bars.find(b => x >= b.x && x <= b.x + b.w && y >= b.y && y <= b.y + b.h);
  showTooltip(hit, e.clientX, e.clientY);
});

For complex shapes, ctx.isPointInPath(path, x, y) tests a Path2D object. Either way, keyboard access does not exist until you build it: focus on the canvas, arrow keys to move between data points, and a live region to announce the current value.

Is a canvas accessible?

To assistive technology, a canvas is an image with no alternative text unless you provide one. Three tools help:

  • Fallback content between <canvas> tags is exposed to screen readers in modern browsers, and it can even contain focusable elements that mirror interactive regions.
  • role="img" with aria-label gives a short summary for simple, static graphics.
  • The data itself, in a nearby table or a “view as table” toggle, is the best alternative for charts. A sentence describing the trend helps everyone, not only screen reader users.

Text drawn with fillText cannot be selected, searched with Find in page, translated or resized with browser text zoom. Keep important text, such as headings and key numbers, in HTML next to the canvas.

Canvas vs SVG: how do you choose?

Question Canvas SVG
How many objects? Thousands to millions Up to a few thousand comfortably
Redraw every frame? Built for it Each change updates the DOM
Pixel manipulation, filters, image editing? Yes, with getImageData Limited
Scales crisply at any zoom? Only if you redraw at the new size Yes, it is vector
Style with CSS, animate with CSS? No Yes
Events and hover per shape? Manual hit testing Built in
Accessible by default? No, needs alternatives Partly: titles, roles, focusable links
Inspectable in DevTools? No, it is pixels Yes, every shape is an element
Typical uses Games, particle effects, heatmaps, large scatter plots, image editors Icons, logos, diagrams, interactive charts with moderate data

For data visualization, a common hybrid works well: draw the dense marks, such as 40,000 points, on canvas, and render axes, labels, legends and the hovered point’s highlight in SVG or HTML layered on top. You get canvas speed and DOM accessibility where it matters.

For 3D or very heavy 2D work, the same element offers a webgl2 context today, and Chrome 113 shipped WebGPU in May 2023 with other browsers working on it. Both use <canvas> as their surface.

Exporting and security

canvas.toBlob() exports the drawing as PNG, JPEG or WebP, which is how browser-based image editors and “download chart” buttons work. Prefer it over toDataURL(), which builds a large string in memory. If you draw an image from another origin without CORS permission, the canvas becomes tainted, and exporting or reading pixels throws a security error. Serve images with Access-Control-Allow-Origin and set crossOrigin = "anonymous" on the image before loading it.

Frequently Asked Questions

When should I use canvas instead of SVG?

Use canvas when you draw thousands of objects, redraw every frame, or need pixel-level manipulation, as in games, particle effects, heatmaps and large scatter plots. Use SVG for icons, diagrams and charts with moderate data, where crisp scaling, CSS styling, per-shape events and accessibility matter more.

Why does my canvas look blurry?

On high-DPI screens, the canvas bitmap is stretched over more physical pixels than it has. Multiply the canvas width and height attributes by window.devicePixelRatio, keep the CSS size unchanged, and scale the context with setTransform so you can keep drawing in CSS pixels.

Is the canvas element accessible?

Not by default. Screen readers see it as an image with no description. Provide fallback content inside the canvas element, a role of img with an aria-label for simple graphics, and the underlying data in HTML, such as a table, for charts.

Should I use setInterval or requestAnimationFrame for canvas animation?

requestAnimationFrame. It syncs drawing with the display’s refresh rate, pauses in background tabs, and avoids drawing frames the user never sees. Scale movement by the time elapsed between frames so speed stays constant on 60 Hz and 120 Hz displays.

Pick the model, then the element

The real choice is between painting pixels yourself and describing shapes for the browser to manage. Paint when volume and speed matter, describe when interaction, styling and accessibility matter, and do not be afraid to layer one over the other. Whichever you pick, scale for the device, animate with the frame clock and give every graphic a text alternative. For the full reference, see the MDN Canvas API guide and the MDN OffscreenCanvas reference. Related reading on this site: web workers.

Originally posted on 8 August 2023 and post last modified on 8 August 2023

Canvas Canvas API Front-End Development HTML5 SVG

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *