Javascript/HTML5 使用图像填充画布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10791610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:02:49  来源:igfitidea点击:

Javascript/HTML5 using image to fill canvas

javascripthtmlcanvas

提问by JDS

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.

问题是什么都没有显示。我能够完成基本的 context.fillRect(..) 示例,但这给我带来了麻烦。

Thanks.

谢谢。

回答by Musa

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

您必须等到图像加载,使用图像的 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();
};