sujesh sujan
sujesh sujan

Reputation: 13

html 5 pattern repeat for canvas

 <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);
 };

I'm trying to use the first canvas as a pattern in the second canvas. It's an example from the Dummies guide. It's just a blank page that appears. I tried setting the background for the mainCanvas as green and it does show up. I guess I am a dummy.

Upvotes: 1

Views: 105

Answers (1)

dc5
dc5

Reputation: 12431

The problem is that you are referring to mainCanvas and not mainContext when drawing on the mainCanvas. (I'm assuming you have a canvas element with and id of mainCanvas)

Change your code to:

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); // <====

Example

Upvotes: 1

Related Questions