CanvasPattern: setTransform() 方法

Baseline 已廣泛支援

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

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

CanvasPattern.setTransform() 方法使用 DOMMatrix 物件作為圖案的變換矩陣,並將其應用到該圖案上。

語法

js
setTransform(matrix)

引數

matrix

用於作為圖案變換矩陣的 DOMMatrix 物件。

返回值

無(undefined)。

示例

使用 setTransform 方法

這是一個程式碼片段,它使用 setTransform 方法,從 DOMMatrix 建立一個具有指定圖案變換的 CanvasPattern。如果您將其設定為當前的 fillStyle,然後使用 fillRect() 方法在畫布上繪製,該圖案就會被應用。

html
<canvas id="canvas"></canvas>
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const matrix = new DOMMatrix([1, 0.2, 0.8, 1, 0, 0]);

const img = new Image();
img.src = "canvas_create_pattern.png";

img.onload = () => {
  const pattern = ctx.createPattern(img, "repeat");
  pattern.setTransform(matrix.rotate(-45).scale(1.5));
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, 400, 400);
};

規範

規範
HTML
# dom-canvaspattern-settransform-dev

瀏覽器相容性

另見