Relatively new to D3, an have a question regarding the translation (animation) of lines. I animate circles using the following code:
var data = d3.range(100).map(function() {
return new agent(
0,
0,
(Math.random()-0.5)*.05,
(Math.random()-0.5)*.05,
'rgb(255, 0, 213)');
});
var circles = canvas.selectAll('circle')
.data(data)
.enter().append('circle')
.attr('cx', function(d) {
return d.x;
})
.attr('cy', function(d) {
return d.y;
})
.attr('r', 5)
.attr('fill', function(d) {
return d.color;
});
circles.attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
The last 3 lines in particular are of interest to me - is there an equivalent translate
for lines?
There are several possible options to animate lines in D3, eg
Changing the underlying data
svg.select(".line")
.duration(animationLength)
.attr("d", valueline(lineData))
valueLine is a d3.svg.line()
function.
Filling the line from start to end via 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 dx; }) .y(function (d) { return dy; }) .interpolate("linear"); var valueline = d3.svg.line() .x(function (d) { return dx * (Math.random() + 0.5); }) .y(function (d) { return dy * (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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.