With d3 it’s possible to animate an element’s position along a <path> element, as seen in this example. The example makes use of the SVGPathElement methods getTotalLength(), which returns the total length of the path, and getPointAtLength(), which returns the x-y position of the path at a specified length.
But the method only works if you want to transition along the entire length of the path. If you want to instead transition to a specific point on the path you need additional tools. Fortunately d3 line generators include a defined() method, which lets you specify which data points are included in the rendered path. Using this, you can create a path segment that spans only the range of your transition.
The source for the examples in this post is available here; alternatively, the relevant files are included inline for you to copy or download.
The first example uses a line generator with linear interpolation:
By default the line segment is transparent; use the “Show segment” checkbox to make it red so you can see the animation path. Clicking the “update” button will generate a new random x value to transition to. The code for the above example is as follows:
Note that on line 113 we generate a new x value that exists as an index in the data set. If nextPoint did not exist as an index—say we set it to 5.5—then the marker would undershoot or overshoot the desired end point. If you’re always transitioning to points that exist in your data set then this is not an issue. The next example shows how to handle cases where you need to transition to arbitrary points.
In this example we use a curveBasis interpolator with the line generator to create a sine curve:
Clicking the “update” button generates a new random [x, y] pair and transitions the circle marker to that point. Unlike the previous example, where the x value always existed as an element in the data set, here x can be any value in the x domain. The trick is found in the update() function, where we add a new entry to our data that corresponds to the generated value. This way our transition will start and stop at the exact desired points.
If you click the checkbox to “Show segment” and click the “Update” button a few times you’ll notice that the red line segment diverges from the blue line in some cases. This is because we’re adding the new data point, which the line interpolator includes in rendering a new line.
While in this case the divergence is tolerable, other cases may demand additional tweaks. There are at least two options:
Here is the code for the second example: