Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 44 ยท Real-world Charts and Integration

Canvas Rendering and Performance

Render large D3 charts on canvas with shape generators and a 2D context, handle hover with quadtree search, mix SVG and canvas layers, and optimize performance.

SVG creates one DOM element for every mark. That is perfect for a few hundred shapes, because every element can be styled, inspected, animated and made accessible. Past a few thousand elements the browser spends its time managing the elements, not drawing them. Canvas is the other approach: a single bitmap element that you paint on with JavaScript commands. There are no elements to keep track of, so ten thousand or a million points are practical.

The price is that canvas is "dumb pixels": nothing remembers what you drew. You must redraw everything when anything changes, and you must implement hover and click detection yourself. D3 helps with both.

Same generators, different output

Scales, layouts and shape generators do not care where the result goes. d3.line(), d3.arc() and d3.geoPath() take an optional context argument; when given a canvas context they issue drawing commands instead of returning a path string:

JavaScript
const ctx = canvas.getContext("2d");
const line = d3.line().x(d => x(d.t)).y(d => y(d.v)).context(ctx);

ctx.beginPath();
line(data);                 // path commands are sent to ctx
ctx.strokeStyle = "steelblue";
ctx.lineWidth = 1.5;
ctx.stroke();

So you can reuse the same scale and generator code as with SVG; only the final painting differs. The same holds for d3.geoPath(projection, ctx) and d3.arc().context(ctx).

Sharp drawing on high-density screens

A canvas has a pixel size (width, height attributes) and a display size (CSS). On retina screens one CSS pixel is two or more device pixels, so a canvas drawn at CSS size looks blurry. Fix it by scaling:

JavaScript
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = width + "px";
canvas.style.height = height + "px";
ctx.scale(dpr, dpr);          // now draw in CSS pixels

Many points: a scatter plot

20,000 points on canvas

The translucent fill makes dense regions darker, a simple way to show density. Try the same with 20,000 <circle> elements in SVG: page load and any interaction would become sluggish.

Hover and click: quadtrees

On canvas there are no elements to listen on, so on pointermove you must find the data point under the cursor. Checking all points is O(n) and too slow per event for big sets. d3.quadtree() indexes points in a spatial tree and finds the nearest point in logarithmic time:

JavaScript
const tree = d3.quadtree()
  .x(d => x(d.x)).y(d => y(d.y))
  .addAll(pts);

canvas.addEventListener("pointermove", event => {
  const [mx, my] = d3.pointer(event);
  const p = tree.find(mx, my, 12);          // nearest within 12 px, or undefined
  if (p) highlight(p); else clearHighlight();
});

Build the tree once after the scales are set (and again if they change). tree.find(x, y, radius) returns the datum, so you can show a tooltip exactly as for SVG (Mouse Events and Tooltips).

Hover a canvas with a quadtree

For irregular shapes (map polygons) another trick is the hit canvas: draw each shape on a hidden canvas with a unique color, then read the pixel under the cursor with getImageData and map the color back to the shape.

Animating canvas

A canvas animation is a loop: clear, draw, repeat on every frame.

JavaScript
d3.timer(elapsed => {
  ctx.clearRect(0, 0, W, H);
  draw(elapsed);            // draw everything for this moment
});

d3.timer calls your function on every animation frame (about 60 times per second) and passes the milliseconds since start; timer.stop() ends it. For tweening you can use d3.interpolate and d3.easeCubicInOut(t) by hand. Force simulations are a natural fit: draw in the tick handler, and large graphs run smoothly.

Layers: SVG and canvas together

You do not have to choose one. Draw the bulk data on canvas and stack an SVG on top (absolutely positioned) for axes, labels, annotations and the hover highlight. Axes then stay crisp, accessible and easy to style, while thousands of marks stay fast. Use pointer-events: none on whichever layer should let events through.

flowchart TD
  D["Data: 50,000 points"] --> C["Canvas layer: marks (fast)"]
  D --> Q["Quadtree for hit testing"]
  S["SVG layer: axes, labels, tooltip marker"] --> V["Viewer"]
  C --> V
  Q --> S

Bulk marks on canvas, details in SVG.

Performance checklist

  1. Measure first with the browser's performance panel; do not optimize blindly.
  2. Prefer one beginPath() with many sub-paths and a single fill() over thousands of separate fills when the style is the same.
  3. Batch by color: draw all points of one group, then the next group, instead of switching fillStyle for each point.
  4. Skip work off-screen and simplify data (aggregation, binning, sampling) for zoomed-out views. Showing 1 million points on 500 pixels is pointless.
  5. Redraw only when needed (on data, size or zoom change), and coalesce repeated events with requestAnimationFrame.
  6. Use OffscreenCanvas and a Web Worker for very heavy drawing, or WebGL (outside D3) for millions of points.
  7. For SVG that must stay SVG, reduce element count, avoid filters and drop shadows, and avoid animating hundreds of elements at once.

Common mistakes

  • Forgetting ctx.beginPath(), so each new shape also strokes everything drawn before.
  • Not clearing the canvas before redrawing animated frames.
  • Blurry output on high-density screens because the device pixel ratio was ignored.
  • Rebuilding the quadtree on every mouse move instead of once per data/scale change.
  • Using canvas when you needed accessible, individually focusable marks; canvas content is invisible to screen readers unless you add a text alternative.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you make d3.line() draw on a canvas instead of producing a path string?

    With a context, the generator issues drawing commands to it. Then you call stroke() or fill().
  2. 2. Why use d3.quadtree for hover on a canvas scatter plot?

    A quadtree answers nearest-point queries quickly, which a flat loop over thousands of points cannot do per mouse event.
  3. 3. What does scaling the context by devicePixelRatio fix?

    The canvas bitmap needs more pixels than CSS pixels on retina screens; the scale lets you keep drawing in CSS pixel units.
  4. 4. What is a good reason to layer SVG over canvas?

    Each technology is used where it is strongest.

Summary

  • Canvas draws bitmaps: great for thousands of marks, but you redraw everything and handle hit testing yourself.
  • D3 generators accept .context(ctx) and scales work unchanged.
  • Use d3.quadtree for hover, d3.timer for animation, and devicePixelRatio for sharp output.
  • Combine canvas marks with SVG axes and overlays; aggregate or sample data when zoomed out.

Next: Accessibility and Testing