这只是一个简单的代码片段,它使用 setTransform
方法从 DOMMatrix
创建具有指定图案变换的 CanvasPattern
。如果您将它设置为当前 fillStyle
并使用 fillRect()
方法进行绘制,该图案就会应用到画布上。
HTML
<canvas id="canvas"></canvas>
JavaScript
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);