d3 shapes

d3 Shapes

d3 comes with various shape generators for arcs, pies, lines, areas, ...

Basically everything that's missing from SVG.

Lines

Lines

SVG paths:

<path d="M 10 10 L 300 200 l -50 -50"></path>

Lines

d3's line generator can be used to generate those nasty d attributes.

var line = d3.line();

svg.append('path')
  .attr('d', line(data));

Lines

Have a look at the docs:

d3-shape#lines

... and turn our bitcoin plot into a line chart!

Curves

Curves

SVG paths can also be used to draw curves:

<path d="M10 80 Q 95 10 180 80"
  stroke="black" fill="transparent"/>

Curves

d3 - again - has some handy generators for curves/arcs: d3.arc()

var arc = d3.arc();
    
arc({
  innerRadius: 0,
  outerRadius: 100,
  startAngle: 0,
  endAngle: Math.PI / 2
});

d3-shape#arc

Curves

Use the d3-template and d3.arc to generate random arcs across a site!

Canvas

Canvas

As a small aside: let's talk about rendering technologies.

Canvas

Canvas is a bitmap-based alternative to SVG's vector format. It is not scalable and opaque.
But it's usually faster!

Canvas

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
  

Canvas

Canvas uses sequential commands with an implicit state for drawing:

ctx.fillStyle = "rgb(200,0,0)";  
ctx.fillRect(10, 10, 55, 50);

Mozilla: CanvasRenderingContext2D

Canvas

Examples:

Stroke rect

Drawing text

Drawing paths

Canvas in d3

Canvas in d3

Since v4.0, canvas is a common option in d3-rendering functions.

Use the .context() function for shape generators to set a canvas context to automatically render to.

Canvas in d3

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var line = d3.line().context(ctx);

ctx.beginPath();
line(data);
...
  

Canvas in d3

Use canvas instead of SVG to draw the bitcoin line chart or the random arcs!

Pie charts

Pie charts

Let's do everyone's favorite: the pie chart.

d3 has a pie generator (d3.pie()) whose result can be plugged into d3.arc.

d3-shape#pie

Pie charts

Let's build a pie chart!

Curves

Curves

d3 has several curve generators:

d3-shape#curves

Curves

You can plug them into the other line- and area-generators:

d3.line()
...
.curve(d3.curveBasis);
  

d3-shape#curves

Area

Area

Generate areas with d3.area():

var area = d3.area()
  .x( ... )
  .y(250)  // baseline
  .y1( ... )

Shapes + Transitions

Shapes + Transitions

The d attribute of paths can also be animated via d3 transitions!

Have a look at code/d3-shapes/01_shape_transitions.html.

Shapes + Transitions

Try building the flowers from the OECD Better-Life-Index based on code/d3-shapes/02_bli_flowers.html.

OECD Better-Life-Index

More

Mike Bostock: Introducing d3-shape

Andy Shora: Tweening Custom Shapes and Paths in d3.js