Friday, September 5, 2014

Animating a geographic boundary into a circle.. Then back again.

Paths in SVG are comprised of points called nodes. In order to transition from one path (the boundary) into another (the circle) the same number of nodes need to exist on both.

Start by drawing a boundary (Texas) with D3.

See the Pen Texas Boundary With D3 by Jamie Popkin (@jamiepopkin) on CodePen.

We want to shrink into a circle that is centred around the centroid of Texas. D3 has a method for finding the centroid. We use this to draw paths from the centroid to each node.

See the Pen Texas With Spokes by Jamie Popkin (@jamiepopkin) on CodePen.

SVG has a handy dandy method for placing a node along the specified distance of a path, getPointAtLength. We use this to calculate a new point at whatever distance from the centroid. In this example we use a radius of 10 pixels. The nice thing about this approach is we can be assured all nodes in the original boundary are accounted for and have a place in the circle.


Finally create a path from the new nodes. We use this to animate the original polygon. D3 makes this pretty simple with the transition method.

VoilĂ .

See the Pen Shrinking Texas With D3 by Jamie Popkin (@jamiepopkin) on CodePen.