此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Path2D.addPath()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2020年1月⁩.

Path2D.addPath() 是 Canvas 2D API 根据指定路径变量添加路径的方法。

语法

js
addPath(path)
addPath(path, transform)

参数

path

需要添加的 Path2D 路径。

transform 可选

DOMMatrix 作为新增路径的变换矩阵。

示例

在已有的路径上添加一条路径

这是一段使用 addPath 方法的简单的代码片段。

HTML

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

JavaScript

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);

结果

规范

Specification
HTML
# dom-path2d-addpath-dev

浏览器兼容性

参见