如何在D3.js中平滑地从起点到终点绘制路径 [英] How to draw a path smoothly from start point to end point in D3.js
本文介绍了如何在D3.js中平滑地从起点到终点绘制路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码根据正弦函数绘制线路径:
I have the following code which plots a line path based on sine function:
var data = d3.range(40).map(function(i) {
return {x: i / 39, y: (Math.sin(i / 3) + 2) / 4};
});
var margin = {top: 10, right: 10, bottom: 20, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
var line = d3.svg.line()
.interpolate('linear')
.x(function(d){ return x(d.x) })
.y(function(d){ return y(d.y) });
var svg = d3.select("body").append("svg")
.datum(data)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("path")
.attr("class", "line")
.attr("d", line);
svg.selectAll('.point')
.data(data)
.enter().append("svg:circle")
.attr("cx", function(d, i){ return x(d.x)})
.attr("cy", function(d, i){ return y(d.y)})
.attr('r', 4);
我想要做的是从第一个节点到最后一个节点平滑地绘制它.我还希望在两个连续节点之间平滑过渡,而不仅仅是一次放置整条线.就像用铅笔连接点一样.
What I want to do is to plot it smoothly from the first node to last node. I also want to have a smooth transition between two consecutive nodes and not just putting the whole line at once. Simply like connecting the dots using a pencil.
任何帮助将不胜感激.
推荐答案
您可以使用 stroke-dashoffset
和 和 path.getTotalLength()
轻松地为路径设置动画>
You can animate paths quite easily with stroke-dashoffset
and and path.getTotalLength()
var totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(2000)
.ease("linear")
.attr("stroke-dashoffset", 0);
这篇关于如何在D3.js中平滑地从起点到终点绘制路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文