如何在D3.js中从起点到终点平滑地绘制path

我有下面的代码,绘制一个基于正弦函数的线path:

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(dx) }) .y(function(d){ return y(dy) }); 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(dx)}) .attr("cy", function(d, i){ return y(dy)}) .attr('r', 4); 

我想要做的就是从第一个节点到最后一个节点平滑地绘制它。 我也想在两个连续的节点之间有一个平滑的过渡,而不是一次把整条线路放在一起。 就像用铅笔连接点一样。

任何帮助将非常感激。

您可以使用stroke-dashoffset and path.getTotalLength()轻松地创buildpath。

 var totalLength = path.node().getTotalLength(); path .attr("stroke-dasharray", totalLength + " " + totalLength) .attr("stroke-dashoffset", totalLength) .transition() .duration(2000) .ease("linear") .attr("stroke-dashoffset", 0); 

http://bl.ocks.org/4063326