Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving a circle along a d3 path animating at varying speeds

Tags:

svg

d3.js

I really found this question and answer helpful on how to get a line animate at varying speeds.

Changing speed of D3 path animation

Which pointed to this block: http://bl.ocks.org/explunit/6082362

I've been following this and would like to add an circle which moves along the start of the line. I've added a marker

    var marker = g.append("circle")
    .attr("r", 7)
    .attr("id", "marker")

but for the life of me I can't get it to follow along the line, at the same speed.

I've added this bit to the end of that block

var p = path.node().getPointAtLength(lengthAt[i-1] );

    markerTransition = markerTransition.transition()
        .duration(lineData[i].speed)
        .ease('linear')
        .attr("transform", "translate(" + p.x + "," + p.y + ")");

and now I have a moving circle, but it's not in sync with the line and is located at different coordinates for some reason.

How can I get my circle to correctly follow along the line at (varying speeds)?

UPDATE: Almost there! I've added a jsfiddle: http://jsfiddle.net/mbrownshoes/k86fbade/6/ Circle is moving at the correct speed to first point, now I need the circle to start each transition from the previous point and not from the beginning.

like image 488
brownshoes Avatar asked Oct 20 '22 16:10

brownshoes


1 Answers

Solved (though going about it another way)

http://jsfiddle.net/mbrownshoes/ozpt6dn7/2/

for (var i = 0; i < lineData.length - 1; ++i) {

wait[i] = tottime;
tottime += lineData[i].t;
setTimeout(function () {
    temp[0] = lineData[ipath];
    temp[1] = lineData[ipath + 1];
    time = lineData[ipath].t;

    var lineGraph = ss.append("path")
        .attr("d", lineFunction(temp))
        .attr("stroke", "grey")
        .attr("stroke-width", 3)
        .attr("fill", "none");



    var totalLength = lineGraph.node().getTotalLength();

    console.log(totalLength);
    console.log(ipath + " " + temp[0].x + " " + temp[1].x + " " + time);

    lineGraph.attr("stroke-dasharray", totalLength + " " + totalLength)
        .attr("stroke-dashoffset", totalLength)
        .transition()
        .duration(time)
        .ease("linear")
        .attr("stroke-dashoffset", 0);

    circle.transition()
        .duration(time)
        .ease("linear")
        .attr("transform",

    function () {


        return "translate(" + temp[1].x + "," + temp[1].y + ")";
    });

    console.log(ipath + ": " + time + ", " + wait);
    ipath++;
}, wait[i]);

}

Thanks to https://groups.google.com/forum/m/#!topic/d3-js/UhaN7HdYTWM

like image 198
brownshoes Avatar answered Oct 22 '22 22:10

brownshoes