此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
CanvasPattern:setTransform() 方法
>备注: 此特性在 Web Worker 中可用。
CanvasPattern.setTransform() 方法使用 DOMMatrix 对象作为图案的变换矩阵,并在当前图案上调用它。
语法
js
setTransform(matrix)
参数
返回值
无(undefined)。
示例
>使用 setTransform 方法
这是一段简单的代码片段,使用 setTransform 方法创建一个来自 DOMMatrix 具有指定图案变化的 CanvasPattern。如例子所示,图案会在其被设置为当前的 fillStyle 时应用;并在使用 fillRect() 方法时会被绘制到 canvas 上。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
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_createpattern.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);
};
可编辑演示
以下是上述代码片段的可编辑演示。尝试更改 SetTransform() 的参数,看看它产生的效果。
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
<input id="edit" type="button" value="Edit" />
<input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code" style="height:120px">
const img = new Image();
img.src = 'canvas_createpattern.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);
};
</textarea>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const edit = document.getElementById("edit");
const code = textarea.value;
const matrix = new DOMMatrix([1, 0.2, 0.8, 1, 0, 0]);
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
}
reset.addEventListener("click", () => {
textarea.value = code;
drawCanvas();
});
edit.addEventListener("click", () => {
textarea.focus();
});
textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);
[フレーム]
规范
| 规范 |
|---|
| HTML> # dom-canvaspattern-settransform-dev> |
浏览器兼容性
启用 JavaScript 以查看此浏览器兼容性表。
参见
- 定义此方法的接口:
CanvasPattern DOMMatrix