Animate line graph line

2019-05-24 21:19发布

I have a stackblitz here - https://stackblitz.com/edit/simple-line-chart?embed=1&file=src/app/bar-chart.ts&hideNavigation=1

Its a simple line graph using D3

I'd like to animate the line from left to right.

Cant find many of this or anything explaing the best way

The actual graph will have a bar chart as well so I cant animate and white block on top to show the line

标签: d3.js svg
2条回答
\"骚年 ilove
2楼-- · 2019-05-24 21:47

Why messing around with a tween function, interpolators and this?

The easiest and most common solution is simply setting the stroke-dasharray and the stroke-dashoffset for the total length...

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

thisLine.attr("stroke-dasharray", totalLength + " " + totalLength)
    .attr("stroke-dashoffset", totalLength);

And then changing it with a simple transition:

thisLine.transition()
    .duration(1000)
    .attr("stroke-dashoffset", 0);

No need for tweening the stroke-dasharray.

Here is the forked code: https://stackblitz.com/edit/simple-line-chart-3hpaje?file=src/app/bar-chart.ts

查看更多
对你真心纯属浪费
3楼-- · 2019-05-24 21:48

It is all a this problem.

  private transition(path) {
    var that = this;
      path.transition()
        .duration(2000)
        .attrTween("stroke-dasharray", that.tweenDash);
  }

  private tweenDash() {
    var l = this.getTotalLength(),
        i = d3.interpolateString("0," + l, l + "," + l);
    return function (t) { return i(t); };
  }

  private drawLine(linedata:any){
    // ....

    var p = this.lineArea.append("path")
      .attr("class", "line")
      .attr("d", valueline(linedata))
      .attr("stroke-linejoin", "round")
      //.call(that.transition)
      ;
    this.transition(p);
  }

Edit

Why do we need i?

This is the same

  private tweenDash() {
    var l = this.getTotalLength();
    return d3.interpolateString("0," + l, l + "," + l);
  }
查看更多
登录 后发表回答