How to find the midPoint of arc in SVG with javascript

时间:2017-11-13 06:44:54

标签: javascript svg

I want to the mid point of arc in svg.. Can any one tell formula to find the midbpoint of arc.,

1 个答案:

答案 0 :(得分:3)

这个问题的答案并不简单。那是因为在SVG中,弧可以是椭圆弧。例如,你会说下一个弧的中点是什么?

<svg width="200" height="200" viewBox="0 0 100 100">
  <path fill="none" stroke="black" stroke-width="2"
        d="M 20,75 A 21,50, 45, 1 1, 60,75"/>
</svg>

无论如何,没有进入复杂的公式,最简单的方法可能是利用SVG的pointAtLength()方法。

var myarc = document.getElementById("myarc");

// Get the length of the path
var pathLen = myarc.getTotalLength();

// How far along the path to we want the position?
var pathDistance = pathLen * 0.5;

// Get the X,Y position
var midpoint = myarc.getPointAtLength(pathDistance)

// For fun, let's add a dot at that position to mark it.
var svg = myarc.ownerSVGElement;
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", midpoint.x);
circle.setAttribute("cy", midpoint.y);
circle.setAttribute("r", "5");
circle.setAttribute("fill", "red");
svg.appendChild(circle);
<svg width="200" height="200" viewBox="0 0 100 100">
  <path id="myarc" fill="none" stroke="black" stroke-width="2"
        d="M 20,75 A 21,50, 45, 1 1, 60,75"/>
</svg>