9

I'm trying to get an image to fill up my canvas. Here is the code I'm trying:

var blueprint_background = new Image();
blueprint_background.src = 'images/blueprint_background.png'; 
var pattern = context.createPattern(blueprint_background, "repeat");

context.fillStyle = pattern;
context.fill();

The issue is that nothing shows up. I was able to do the the basic context.fillRect(..) example, but this is giving me troubles.

Thanks.

JDS
  • 16,388
  • 47
  • 161
  • 224

2 Answers2

12

You have to wait until the image loads, use the image's onload property to know when it loads.

var blueprint_background = new Image();
blueprint_background.src = 'images/blueprint_background.png'; 
blueprint_background.onload = function(){
    var pattern = context.createPattern(this, "repeat");
    context.fillStyle = pattern;
    context.fill();
};
Musa
  • 96,336
  • 17
  • 118
  • 137
  • I'm seeing mismatched parenthesis? I'm not too familiar with javascript. EDIT - tried removing the ')' to fix the syntax error but the image still didn't load – JDS May 29 '12 at 00:18
  • Oi, I fixed it by adding (just before context.fill()): context.rect(x,y,width,height); Then it did exactly what I wanted. – JDS May 29 '12 at 00:25
0

Be aware if someone wants to create pattern from image within Worker.

Inside Worker class Image is not defined!

ReferenceError: Image is not defined

In such case we can do the following:

const result = await fetch('./image.png');
const blob = await result.blob();
const image = await createImageBitmap(blob);
const pattern = canvasContext2D.createPattern(image, 'repeat');

And then simply fill OffscreenCanvasContext2D:

canvasContext2D.fillStyle = pattern;
canvasContext2D.fill();

References:

Mateusz Budzisz
  • 598
  • 7
  • 15