在HTML5中使用drawImage [英] Using drawImage in HTML5

查看:91
本文介绍了在HTML5中使用drawImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事实:以下代码有效。

var img = new Image();
img.onload = function() {
    context.drawImage(img, 32, 32);
};
img.src = "example.png";

第一次观察:以下内容不会绘制到画布。

First Observation : The following will not draw to canvas.

var img = new Image();
img.src = "example.png";
context.drawImage(img, 32, 32);

第二次观察:以下内容将绘制到画布(最终)......

Second Observation : The following will draw to canvas (eventually)...

var img = new Image();
img.src = "example.png";
setInterval(function() {context.drawImage(img, 32, 32);}, 1000);






为什么我需要调用drawImage回调函数?如果是这种情况,为什么它最终在嵌套在setInterval函数中时有效?


Why is it that I need to call the drawImage function on a callback? And if that is the case, why does it eventually work when nested in a setInterval function?

推荐答案

当你设置 src 的图像对象,浏览器开始下载它。但是,在浏览器执行下一行代码时,您可能会或可能不会加载该图像。这就是为什么你要绘制一个空白图像,因为它尚未加载。

When you set the src of the image object, the browser starts to download it. But you may or may not get that image loaded by the time the browser executes the next line of code. That's why you are drawing a "blank" image, because it ain't loaded just yet.

你需要放置一个 onload 处理程序,知道图像何时完成加载。只有这样你才能把它画到画布上:

You need to place an onload handler to know when the image has finished loading. Only then will you draw it to the canvas:

var img = new Image();             //create image object
img.onload = function(){           //create our handler
  context.drawImage(img, 32, 32);  //when image finishes loading, draw it
}
img.src = "example.png";           //load 'em up!

这篇关于在HTML5中使用drawImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆