如何用javascript在SVG中找到arc的midPoint [英] How to find the midPoint of arc in SVG with javascript

查看:65
本文介绍了如何用javascript在SVG中找到arc的midPoint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望svg中的弧的中点..任何人都可以告诉公式找到弧的中点。

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

推荐答案

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

The answer to that question is not straightforward. That's because in SVG arcs can be an elliptical arc. For example, what would you say is the midpoint on the following arc?

<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()方法。

Anyway, without getting into complicated formulae, the simplest method is probably to take advantage of SVG's pointAtLength() method.

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>

这篇关于如何用javascript在SVG中找到arc的midPoint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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