onTheInternet
onTheInternet

Reputation: 7263

How to animate line graph in D3

I have a project that I'm working on that was inspired by the Amazing NYTimes Interactive Charts where you would draw the chart and see how you did compared to real data. I want to make a simple version of that using D3.

Here is my working codepen so far

It is rough but it works.

What I want to do, however, is to have the line be 'drawn' across the graph once the user clicks 'How did I do?'

This is a great example of what I'm after with the second line

I followed the above example and added a transition to the javascript like so.

function addSecondLine(){
    focus.append("path")
        .datum(morePoints)
        .attr("fill", "none")
        .attr("stroke", "green")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("stroke-width", 1.5)
        .attr("d", line)
        .transition()
        .duration(4000);
}

But that didn't achieve anything.

Upvotes: 1

Views: 1718

Answers (2)

Shreya
Shreya

Reputation: 171

https://codepen.io/shreya0712/pen/ZEYYrMd?editors=1010

I hope this is what you'd been trying.

    function addSecondLine() {
      var line2 = focus
        .append("path")
        .datum(morePoints)
        .attr("fill", "none")
        .attr("stroke", "green")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("stroke-width", 1.5)
        .attr("d", line);

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

      line2
        .attr("stroke-dasharray", totalLength)
        .attr("stroke-dashoffset", totalLength)
        .transition()
        .duration(2000)
        .attr("stroke-dashoffset", 0);
    }

Upvotes: 3

Martin
Martin

Reputation: 562

This effect is done using the stroke-dashoffset property. Right now in your code, you're making a transition toward nothing.

First you need to set the offset to the total length of your path, then you'll need to make a transition to an offset of 0.

This is clear in the example you provided.

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

Upvotes: 2

Related Questions