首页 > 解决方案 > d3.js 中的路径转换不起作用

问题描述

我正在尝试在 d3.js 中的路径上进行转换。当用户点击一个按钮时,路径上应该有一个从路径开始到结束的过渡。

我尝试用这段代码做到这一点:

const lineGraph = d3.select("svg")
  .append("path")
  .attr("d", "M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80");

const length = lineGraph.node().getTotalLength();

lineGraph
  .attr("stroke-dasharray", length + " " + length)
  .transition()
  .duration(2000)
  .ease(d3.easeLinear);
path {
  stroke: black;
  stroke-width: 1px;
  fill: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>

路径显示在屏幕上,但没有过渡。

标签: javascriptd3.jsecmascript-6

解决方案


那是因为你需要某事过渡其他事。在出现路径的情况下,即从 stroke-dasharray0 lengthlength length

const lineGraph = d3.select("svg")
  .append("path")
  .attr("d", "M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80");

const length = lineGraph.node().getTotalLength();

lineGraph
  .attr("stroke-dasharray", "0 " + length)
  .transition()
  .duration(2000)
  .ease(d3.easeLinear)
  .attr("stroke-dasharray", length + " " + length);
path {
  stroke: black;
  stroke-width: 1px;
  fill: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>


推荐阅读