4

我遇到了困难.createPattern(image,"repeat")

  1. 我可以用.toDataURL()and创建的自己的图案填充一个正方形.createPattern()吗?
  2. 我可以用当前画布的图案填充正方形吗?

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

context.strokeRect(0.5, 0.5, 10, 10);
context.arc(5.5, 5.5, 3, 0, Math.PI);
context.rect(3, 3, 1, 1);
context.rect(7, 3, 1, 1);
context.stroke();

var img = new Image();
img.src = canvas.toDataURL();
context.drawImage(img, 10, 10); // works

context.beginPath();
var pattern = context.createPattern(img, "repeat"); // doesn't work
context.fillStyle = pattern;
context.fillRect(20, 20, 100, 100);
context.fill();

context.beginPath();
var pattern2 = context.createPattern(canvas, "repeat"); // doesn't work
context.fillStyle = pattern2;
context.fillRect(120, 20, 100, 100);
context.fill();
<canvas id="canvas" width="320" height="240" style="border: solid darkblue 1px;background-color: aliceblue"></canvas>

4

1 回答 1

7

您将需要为模式创建一个单独的画布,因为您不能自引用画布以用于模式。

原因是当您引用您尝试绘制的原始画布时,图案将具有相同的大小,并且只会绘制一个实例,因为没有更多空间。

因此,要使其工作,您需要定义一个较小尺寸的图案,因此我们需要一个单独的画布或图像并将其作为图案的源传递。

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

// create the off-screen canvas
var canvasPattern = document.createElement("canvas");
canvasPattern.width = 10;
canvasPattern.height = 10;
var contextPattern = canvasPattern.getContext("2d");

// draw pattern to off-screen context
contextPattern.beginPath();
contextPattern.strokeRect(0.5, 0.5, 10, 10);
contextPattern.arc(5.5, 5.5, 3, 0, Math.PI);
contextPattern.rect(3, 3, 1, 1);
contextPattern.rect(7, 3, 1, 1);
contextPattern.stroke();

// now pattern will work with canvas element    
var pattern = context.createPattern(canvasPattern,"repeat");
context.fillStyle = pattern;
context.fillRect(20, 20, 100, 100);
context.fill();
<canvas id="canvas" width="320" height="240" style="border: solid darkblue 1px;background-color: aliceblue"></canvas>

于 2013-07-08T01:53:04.720 回答