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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13893127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:04:51  来源:igfitidea点击:

How to draw a path smoothly from start point to end point in D3.js

javascriptsvgd3.js

提问by Nasir

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.

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

Any help would be really appreciated.

任何帮助将非常感激。

回答by methodofaction

You can animate paths quite easily with stroke-dashoffsetand and path.getTotalLength()

您可以使用stroke-dashoffset和轻松地为路径设置动画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);

http://bl.ocks.org/4063326

http://bl.ocks.org/4063326