Ashwin Prasad
Ashwin Prasad

Reputation: 128

Drawing D3 paths one after the other

I'm trying to create a location tracing POC,where there will be multiple points and each of these points would be connected a path. I want to draw a path between two points first and then move on to the next two points. I don't want to include all the points in the same path.Each two points should have a unique path since i want to control the transition duration of each path drawn.

  var ss =  d3.select('#chart')
 .append('svg')
 .attr('width', 760)
 .attr('height', 690)
 .style('background', "#93A1A1")

 //The data for my line
 var lineData = [ { "x": 10,   "y": 5 , "t":7000},  { "x": 200,  "y": 20, "t":8000},
 { "x": 400,  "y": 10, "t":9000}, { "x": 250,  "y": 40, "t":1000},
 { "x": 350,  "y": 200, "t":10000},{ "x": 200,  "y": 500, "t":11000},
 { "x": 120, "y": 80, "t":9000},{ "x": 100,   "y": 500, "t":9000},{ "x": 100,   "y": 50, "t":8000}];

 //Function to draw line
 var lineFunction = d3.svg.line()
 .x(function(d) { return d.x; })
 .y(function(d) {return d.y; })

 var temp = [];

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

 temp[0] = lineData[i];
 temp[1] = lineData[i+1];
 time =  lineData[i].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(i+" "+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);
 }

This is my code so far,when i run this all the lines are being drawn but i need each path to be drawn one after the other. Here is the Demo JSFiddle

Upvotes: 1

Views: 883

Answers (1)

Robert Longson
Robert Longson

Reputation: 123985

Use delay to start each subsequent animation when the previous one has finished i.e.

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

    temp[0] = lineData[i];
    temp[1] = lineData[i + 1];
    time = lineData[i].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(i + " " + temp[0].x + " " + temp[1].x + " " + time);

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

    totalTime += time;

}

or as a jsfiddle

Upvotes: 2

Related Questions