Livecoding: A Map of Global Migrations, Part 3
In the third and final part of our series, we're going to to use React and D3 to animate our SVG elements, so they'll follow a curve. Which maps the map look great!
Join the DZone community and get the full member experience.
Join For Free
Since finishing Part 1 and Part 2, we've built a zoomable pannable map with React and D3. We also added animation to our migration curves. Now people can see what they mean.
See? It zooms and it pans and the circles follow their curves. Just like the color, the amount of circles on each line signifies migration intensity.
Here's how it works.
Animate the SVG Element to Follow a Curve
Moving an element along a line is one of those things you think you can figure out on your own but you can't. Then you see how it's done and you think, "I'm dumb."
But you're not dumb. It's totally un-obvious.
We used Bostock's Point-Along-Line Interpolation example as our model. It creates a custom tween that we apply to each circle as an attrTween
transition.
function translateAlong(path) {
var l = path.getTotalLength();
return function(d, i, a) {
return function(t) {
var p = path.getPointAtLength(t * l);
return "translate(" + p.x + "," + p.y + ")";
};
};
}
That's the custom tween. I'd love to explain how it works, but… well, we have a getPointAtLength
function that SVG gives us by default on every <path>
element. We use it to generate translate(x, y)
strings that we feed into the transform
attribute of a <circle>
element. That part is obvious.
The part I don't get is the 3-deep function nesting for currying. The top function returns a tween, I assume. It's a function that takes d, i, a
as arguments and never uses them. Instead, it returns a time-parametrized function that returns a translate(x, y)
string for each t
.
We know from D3 conventions that t
runs in the [0, 1]
interval, so we can assume that the tween gives a "point at t percent of full length of path" coordinates.
Great.
We apply it in our MigrationLine
component like this:
// inside MigrationLine
_transform(circle, delay) {
const { start } = this.props,
[ x1, y1 ] = start;
d3.select(circle)
.attr("transform", `translate(${x1}, ${y1})`)
.transition()
.delay(delay)
.duration(this.duration)
.attrTween("transform", translateAlong(this.refs.path))
.on("end", () => {
if (this.state.keepAnimating) {
this._transform(circle, 0);
}
});
}
componentDidMount() {
const { Ncircles } = this.props;
this.setState({
keepAnimating: true
});
const delayDither = this.duration*Math.random(),
spread = this.duration/Ncircles;
d3.range(delayDither, this.duration+delayDither, spread)
.forEach((delay, i) =>
this._transform(this.refs[`circles-${i}`], delay)
);
}
We call _transform
on every circle in our component. Each gets a different delay
so that we get a roughly uniform distribution of circles on the line. Without this, they come in bursts, and it looks weird.
delayDither
ensures the circles for each line start with a random offset, which also helps fight the burstiness. Here's what the map looks like without delayDither
and with a constant delay between circles regardless how many there are.
See? No good.
You can see the full MigrationLine code on Github.
Zoom and Pan a Map
This part was both harder and easier than I thought.
You see, D3 comes with something called d3.zoom. It does zooming and panning.
Cool, right? Should be easy to implement. And it is… if you don't fall down a rabbit hole.
In the old days, the standard approach was to .call()
zoom on an <svg>
element, listen for zoom
events, and adjust your scales. Zoom callback would tell you how to change zoominess and where to move, and you'd adjust your scales and re-render the visualization.
We tried that approach with hilarious results:
First, it was moving in the wrong direction, then it was jumping around. Changing the geo projection to achieve zoom and pan was not the answer. Something was amiss.
Turns out in D3v4, the zoom callback gets info to build an SVG transform. A translate()
followed by a scale()
.
Apply those on the visualization and you get working zooming and panning functionalities! Of anything!
// in SVG rendering component
onZoom() {
this.setState({
transform: d3.event.transform
});
}
get transform() {
if (this.state.transform) {
const { x, y, k } = this.state.transform;
return `translate(${x}, ${y}) scale(${k})`;
}else{
return null;
}
}
// ...
render() {
return (
<svg width={width} height={height} ref="svg">
<g transform={this.transform}>
// ...
}
Get d3.event.transform
, save it in state
or a data store of some sort, re-render, use it on a <g>
element that wraps everything.
Voila, zooming and panning.
You can see the full World
component on Github.
Happy hacking!
Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments