Skip to content

Canvas ​

The Canvas renderer draws shapes with the Canvas 2D API. It draws every shape, one by one, clips, and supports transitions. It suits animations and thousands of shapes per frame; for ASCII art, use the Terminal.

js
const renderer = cm.canvas({width: 640, height: 200});
const root = cm.flow().renderer(renderer);

root.append(cm.clear, {fill: "black"});
root.data(d3.range(60)).append(cm.circle, {
  x: (d) => 20 + d * 10,
  y: (d) => 100 + Math.sin(d / 4) * 60,
  r: (d) => 4 + Math.abs(Math.cos(d / 4)) * 8,
  fill: "white",
  fillOpacity: 0.8,
});

root.render();
document.body.append(renderer.node());

cm.canvas([options]) ​

Returns a renderer that draws into a canvas element. Options:

  • width — the CSS width in pixels (default 640).
  • height — the CSS height in pixels (default 480).
  • dpi — the pixel ratio of the backing store (default window.devicePixelRatio).

As for SVG, a width or height that isn't given is auto: a transform such as cm.plane may resize it. Charts and their interactions work on Canvas as on SVG; see the canvas tip example.

js
const renderer = cm.canvas({width: 200, height: 100});

renderer.node() ​

Returns the canvas element, to add to the page.

js
document.body.append(renderer.node());

Animating ​

A canvas keeps what it drew. A flow built anew for each frame draws over the last one, so a frame usually starts with cm.clear; a flow drawn again, such as for a signal or a transition, erases the canvas first.

js
const renderer = cm.canvas({width: 640, height: 160});
const root = cm.flow().renderer(renderer);
let t = 0;

requestAnimationFrame(function frame() {
  t += 0.03;
  root.append(cm.clear, {fill: "rgba(255, 255, 255, 0.2)"});
  root.append(cm.circle, {x: 320 + Math.cos(t) * 260, y: 80 + Math.sin(t * 2) * 50, r: 20, fill: "black"});
  root.render();
  requestAnimationFrame(frame);
});

document.body.append(renderer.node());