<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);
};
我正在尝试将第一个画布用作第二个画布中的模式。这是傻瓜指南中的一个例子。它只是一个空白页面出现。我尝试将mainCanvas的背景设置为绿色,它确实显示出来。我想我是个假人。
答案 0 :(得分:1)
问题是,在mainCanvas上绘图时,您指的是mainCanvas
而不是mainContext
。 (我假设你有一个带有和mainCanvas id的canvas元素)
将您的代码更改为:
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); // <====