Reputation: 4980
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
Upvotes: 2
Views: 181
Reputation: 102219
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
Upvotes: 1
Reputation: 28848
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);
}
Upvotes: 2