I have a simple path element that a circle has to follow using D3.js. I found a way to do this through using getTotalLength and getPointAtLength methods on SVG as described in this example:
http://bl.ocks.org/mbostock/1705868
It works fine but the problem is that my circle starts at the bottom and follows the line upwards, how do i change the starting point of the circle in the animation so it goes from top to bottom? Here's my code:
my path element:
<path id="testpath" style="fill:none;stroke:#FFFFFF;stroke-width:0.75;" d="M1312.193,1035.872l80.324-174.458l13.909-264.839l507.09-211.095
l8.667-248.405" />
the D3 code:
function followPath()
{
var circle = d3.select("svg").append("circle")
.attr("r", 6.5)
.attr("transform", "translate(0,0)")
.attr("class","circle");
var path = d3.select("#testpath");
function transition()
{
circle.transition()
.duration(10000)
.attrTween("transform", translateAlong(path.node()))
.each("end", 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 + ")";
};
};
}
transition();
}
I made a fiddle where u can see it going from bottom to top(i know the viewbox is big, it's part of a much bigger SVG image)
The animation will start at the start of the line, as defined in the SVG. To make it start at an arbitrary point, you have to offset it accordingly. To get the exact opposite as in your case, the change is almost trivial though -- you just start at the end and move towards the beginning. That is, you "invert" the transition by considering
1-t
instead oft
:Complete demo here.