如何在D3.js中从起点到终点平滑绘制路径 [英] How to draw a path smoothly from start point to end point in D3.js

查看:864
本文介绍了如何在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.

任何帮助都会非常感激。

Any help would be really appreciated.

推荐答案

您可以使用 stroke-dashoffset 和path.getTotalLength() / p>

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);

http:/ /bl.ocks.org/4063326

这篇关于如何在D3.js中从起点到终点平滑绘制路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆