This is a Livecoding Recap – an almost-weekly post about interesting things discovered while livecoding ?. Always under 500 words and with pictures. You can follow my channel, here. New content almost every Sunday at 2pm PDT. There’s live chat, come say hai ?

This Sunday, we built a zoomable pannable map with React and D3. We also added animation to our migration curves. Now people can see what they mean.

Click on the map to see a live example

Click on the map to see a live example

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 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 the tween gives a "point at t percent of full length of path" coordinates.


We apply it in our MigrationLine component like this:

// inside MigrationLine
    _transform(circle, delay) {
        const { start } = this.props,
              [ x1, y1 ] = start;

          .attr("transform", `translate(${x1}, ${y1})`)
          .attrTween("transform", translateAlong(this.refs.path))
          .on("end", () => {
              if (this.state.keepAnimating) {
                  this._transform(circle, 0);
    componentDidMount() {
        const { Ncircles } = this.props;
            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! Of anything 😀

// in SVG rendering component
    onZoom() {
            transform: d3.event.transform
    get transform() {
        if (this.state.transform) {
            const { x, y, k } = this.state.transform;
            return `translate(${x}, ${y}) scale(${k})`;
            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. ?

Click on the map to see a live example

Click on the map to see a live example

You can see the full World component on Github.

Happy hacking! ?

Learned something new? Want to become a better engineer? 💌

Join 9,400+ people just like you already improving their skills.

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖 right away. After that you'll get a thoughtfully written email every week about React, JavaScript,  and lessons learned in my 20 years of writing code for companies ranging from tiny startups to Fortune5 behemoths.

Man, I love your way of writing these newsletters. Often very relatable and funny perspectives about the mundane struggles of a dev. Lightens up my day. ~ Kostas

PS: You should also follow me on twitter 👉 here.
It's where I go to shoot the shit about programming.