最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - JavascriptHTML5 using image to fill canvas - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked May 28, 2012 at 23:56 JDSJDS 17k47 gold badges168 silver badges233 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

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

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:

  • OffscreenCanvas - developer.mozilla.org
  • OffscreenCanvasRenderingContext2D - html.spec.whatwg.org
  • Worker - developer.mozilla.org
  • Fetch - developer.mozilla.org
  • Blob - developer.mozilla.org
  • createImageBitmap - developer.mozilla.org
  • createPattern - html.spec.whatwg.org
发布评论

评论列表(0)

  1. 暂无评论