d3js 如何在两端画一条线,使其在中间相交?

d3js How to draw a line by both ends so it meet at the middle?

我看到我们可以通过 stroke-dasharray 动画绘制笔划,例如:

var svg = d3.select("body").append("svg")
  .attr("width", 300)
  .attr("height", 300);

var path = svg.append("path")
  .attr("d", "M10,10 50,20, 100,30 110,40 100,50 50,40 10,10 Z")
  .attr("style", "stroke:#666;stroke-width:6px;fill:none;");

var totalLength = path.node().getTotalLength();

path.attr("stroke-dasharray", totalLength + "," + totalLength)
  .attr("stroke-dashoffset", totalLength) // = eat how much of the black dash ?
  .transition()
  .duration(2000)
  .ease("linear")
  .attr("stroke-dashoffset", 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

但是两条动画线在中间相遇怎么画呢?

试试这个,它应该有效:)

var svg = d3.select("body").append("svg")
  .attr("width", 300)
  .attr("height", 300);

var path = svg.append("path")
  .attr("d", "M0,30 L30,5 L60,30 S70,20 90,7 S120,10 120,30")
  .attr("style", "stroke:#666;stroke-width:6px;fill:none;");

var totalLength = path.node().getTotalLength();

path.attr("stroke-dasharray", totalLength + "," + totalLength)
  .attr("stroke-dashoffset", totalLength) // = eat how much of the black dash ?
  .transition()
  .duration(2000)
  .ease("linear")
  .attr("stroke-dashoffset", totalLength * 1/2) // gives the meeting point.
  .attr("stroke-dasharray", totalLength + "," + 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

它也适用于除中间以外的其他比例,但您必须提供此比例。