1
 <canvas id="textureCanvas" width="3" height="1">what kind of cheap ass browser are you using? (I'm joking... something went wrong)</canvas>

   window.onload = function () {
var mainCanvas = document.getElementById('mainCanvas');
var textureCanvas = document.getElementById('textureCanvas');

var mainContext = mainCanvas.getContext('2d');
var textureContext = textureCanvas.getContext('2d');

textureContext.fillStyle = 'grey';
textureContext.fillRect(0, 0, 1, 1);

textureContext.fillStyle = 'lightgrey';
textureContext.fillRect(1, 0, 1, 1);

textureContext.fillStyle = 'grey';
textureContext.fillRect(2, 0, 1, 1);

var pattern = mainCanvas.createPattern(textureCanvas, 'repeat');

mainCanvas.fillStyle = pattern;

mainCanvas.fillRect(0, 0, 198, 99);
 };

我正在尝试将第一个画布用作第二个画布中的图案。这是 Dummies 指南中的一个示例。它只是出现一个空白页面。我尝试将 mainCanvas 的背景设置为绿色,它确实出现了。我想我是个假人。

4

1 回答 1

1

问题是您指的是mainCanvas而不是mainContext在 mainCanvas 上绘图时。(我假设你有一个画布元素,其 ID 为 mainCanvas)

将您的代码更改为:

var mainCanvas = document.getElementById('mainCanvas');
var textureCanvas = document.getElementById('textureCanvas');

var mainContext = mainCanvas.getContext('2d');
var textureContext = textureCanvas.getContext('2d');

textureContext.fillStyle = 'grey';
textureContext.fillRect(0, 0, 1, 1);

textureContext.fillStyle = 'lightgrey';
textureContext.fillRect(1, 0, 1, 1);

textureContext.fillStyle = 'grey';
textureContext.fillRect(2, 0, 1, 1);

var pattern = mainContext.createPattern(textureCanvas, 'repeat'); // <====

mainContext.fillStyle = pattern; // <====

mainContext.fillRect(0, 0, 198, 99); // <====

例子

于 2013-08-28T00:09:47.910 回答