SVGPathElement: getPointAtLength() 方法

getPointAtLength() 方法是 SVGPathElement 接口的一部分,它返回沿路径给定距离的点。

语法

js
getPointAtLength(distance)

参数

distance

一个数字,表示沿路径的距离

返回值

一个 DOMPoint 对象,表示沿路径给定距离的点。

示例

获取 <path> 的中点

在此示例中,我们通过获取路径长度一半的点来确定路径的中点。

我们定义了一个包含两条路径的 SVG:一条基本线段和一条复杂的爱心形状。

创建爱心的路径大约有 275 个单位长。

html
<svg width="200" height="100">
  <path
    id="heart"
    fill="red"
    d="M 10,30
           A 20,20 0,0,1 50,30
           A 20,20 0,0,1 90,30
           Q 90,60 50,90
           Q 10,60 10,30 z" />
  <path id="line" d="M 0,30 h100" stroke="black" />
</svg>

水平线段从 0, 30 开始,长度为 100 个单位。爱心路径从 10, 30 开始,大约有 275 个单位长。

我们知道线段的长度是 100 个单位,因此 50 是中点。我们使用 SVGPathElement.getTotalLength() 方法来获取爱心路径的长度,并将其除以 2 来获得中点距离。然后,我们使用 getPointAtLength() 方法将中点作为 DOMPoint 对象返回。我们显示每个中点的 xy 坐标。

js
const basicPath = document.getElementById("line");
const complexPath = document.getElementById("heart");

// Get the length of the heart and divide by 2
const halfLength = complexPath.getTotalLength() / 2;

// Access the getPointAtLength property
const basicMidPoint = basicPath.getPointAtLength(50);
const complexMidPoint = complexPath.getPointAtLength(halfLength);

// The base value of the pathLength attribute
log(`Line mid point: ${basicMidPoint.x}, ${basicMidPoint.y}`);
log(`Heart mid point: ${complexMidPoint.x}, ${complexMidPoint.y}`);

规范

规范
SVG 路径
# __svg__SVGPathElement__getPointAtLength

浏览器兼容性

另见