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

瀏覽器相容性

另見