Path2D: addPath() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

注意:此功能在 Web Workers 中可用。

Canvas 2D API 的 Path2D.addPath() 方法將一個 Path2D 物件新增到另一個 Path2D 物件。

語法

js
addPath(path)
addPath(path, transform)

引數

路徑

要新增的 Path2D 路徑。

transform 可選

將用作所新增路徑的變換矩陣的 DOMMatrix。(技術上講,是指一個具有與 DOMMatrix 物件相同屬性的物件。)

返回值

無(undefined)。

示例

將一個路徑新增到現有路徑

此示例將一個路徑新增到另一個路徑。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

首先,我們建立兩個獨立的 Path2D 物件,每個物件都包含一個使用 rect() 方法建立的矩形。然後,我們使用 DOMMatrix() 建立一個矩陣。接著,我們使用 addPath() 方法將第二個路徑新增到第一個路徑,並應用矩陣將第二個路徑向右移動。最後,我們使用 fill() 方法繪製第一個路徑(該路徑現在包含兩個矩形)。

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Create first path and add a rectangle
let p1 = new Path2D();
p1.rect(0, 0, 100, 150);

// Create second path and add a rectangle
let p2 = new Path2D();
p2.rect(0, 0, 100, 75);

// Create transformation matrix that moves 200 points to the right
let m = new DOMMatrix();
m.a = 1;
m.b = 0;
m.c = 0;
m.d = 1;
m.e = 200;
m.f = 0;

// Add second path to the first path
p1.addPath(p2, m);

// Draw the first path
ctx.fill(p1);

結果

規範

規範
HTML
# dom-path2d-addpath-dev

瀏覽器相容性

另見

  • 定義此方法的介面:Path2D