d3 comes with various shape generators for arcs, pies, lines, areas, ...
Basically everything that's missing from SVG.
SVG paths:
<path d="M 10 10 L 300 200 l -50 -50"></path>
d3's line generator can be used to generate those nasty d
attributes.
var line = d3.line();
svg.append('path')
.attr('d', line(data));
Have a look at the docs:
d3-shape#lines
... and turn our bitcoin plot into a line chart!
SVG paths can also be used to draw curves:
<path d="M10 80 Q 95 10 180 80"
stroke="black" fill="transparent"/>
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
Use the d3-template and d3.arc to generate random arcs across a site!
As a small aside: let's talk about rendering technologies.
Canvas is a bitmap-based alternative to SVG's vector format. It is not scalable and opaque.
But it's usually faster!
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
Canvas uses sequential commands with an implicit state for drawing:
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect(10, 10, 55, 50);
Mozilla: CanvasRenderingContext2D
Examples:
Stroke rect
Drawing text
Drawing paths
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.
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var line = d3.line().context(ctx);
ctx.beginPath();
line(data);
...
Use canvas instead of SVG to draw the bitcoin line chart or the random arcs!
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
Let's build a pie chart!
d3 has several curve generators:
d3-shape#curves
You can plug them into the other line- and area-generators:
d3.line()
...
.curve(d3.curveBasis);
d3-shape#curves
Generate areas with d3.area()
:
var area = d3.area()
.x( ... )
.y(250) // baseline
.y1( ... )
The d
attribute of paths can also be animated via d3 transitions!
Have a look at code/d3-shapes/01_shape_transitions.html.
Try building the flowers from the OECD Better-Life-Index based on code/d3-shapes/02_bli_flowers.html.
OECD Better-Life-Index
Mike Bostock: Introducing d3-shape
Andy Shora: Tweening Custom Shapes and Paths in d3.js