8

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.

4

2 に答える 2

12

画像が読み込まれるまで待つ必要があります。画像の onload プロパティを使用して、いつ読み込まれるかを確認してください。

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();
};
于 2012-05-29T00:07:55.477 に答える
0

誰かが Worker 内の画像からパターンを作成したい場合は注意してください。

内部 Worker クラス イメージが定義されていません!

ReferenceError: Image is not defined

このような場合、次のことができます。

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

そして、単に OffscreenCanvasContext2D に入力します:

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

参考文献:

于 2021-08-04T20:59:19.130 に答える