There are multiple ways to animate lines in D3, for example:
Modifying the data
svg.select(".line")
.duration(animationLength)
.attr("d", valueline(lineData))
valueline represents a d3.svg.line()
function.
Animating line fill from start to end using stroke-dashoffset
var lineGraph = svg.append("path")
.attr("class", "line")
.attr("d", lineFunction(lineData))
.attr("stroke-dasharray", 200 + " " + 200)
.attr("stroke-dashoffset", 200)
.attr("fill", "none")
.transition()
.duration(animationLength)
.ease("linear")
.attr("stroke-dashoffset", 0);
Using transform
to move the line
svg.select(".line")
.duration(animationLength)
.attr("transform", "translate(" + 100 * Math.random() + "," + 100 * Math.random() + ")");
var animationLength = 2000;
var lineData = [{
"x": 1,
"y": 5
}, {
"x": 20,
"y": 20
}, {
"x": 40,
"y": 10
}, {
"x": 60,
"y": 40
}, {
"x": 80,
"y": 5
}, {
"x": 100,
"y": 60
}];
var lineFunction = d3.svg.line()
.x(function (d) {
return d.x;
})
.y(function (d) {
return d.y;
})
.interpolate("linear");
var valueline = d3.svg.line()
.x(function (d) {
return d.x * (Math.random() + 0.5);
})
.y(function (d) {
return d.y * (Math.random() + 0.5);
});
var svg = d3.select("#line")
.append("svg")
.attr("width", 200)
.attr("height", 200);
var lineGraph = svg.append("path")
.attr("class", "line")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("stroke-dasharray", 200 + " " + 200)
.attr("stroke-dashoffset", 200)
.attr("fill", "none")
.transition()
.duration(animationLength)
.ease("linear")
.attr("stroke-dashoffset", 0);
svg = d3.select("body").transition();
svg.select(".line")
.delay(animationLength)
.duration(animationLength)
.attr("d", valueline(lineData))
.attr("transform", "translate(" + 100 * Math.random() + "," + 100 * Math.random() + ")");
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="line"></div>