简体   繁体   English

在HTML5中使用drawImage

[英]Using drawImage in HTML5

Fact : The following code is valid. 事实:以下代码有效。

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

Why is it that I need to call the drawImage function on a callback? 为什么需要在回调上调用drawImage函数? And if that is the case, why does it eventually work when nested in a setInterval function? 如果是这种情况,为什么嵌套在setInterval函数中后最终可以起作用?

When you set the src of the image object, the browser starts to download it. 设置图像对象的src后,浏览器将开始下载它。 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. 这就是为什么要绘制“空白”图像的原因,因为它尚未加载。

You need to place an onload handler to know when the image has finished loading. 您需要放置一个onload处理程序,以了解映像何时完成加载。 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!

You can only draw the image to canvas after it's loaded, that's why it works when you do it from the onload callback. 您只能在图像加载后将其绘制到画布上,这就是为什么从onload回调中进行操作时图像可以起作用的原因。 And it works with setInterval because, after a certain amount of time, it eventually gets fully loaded. 它可以与setInterval一起使用,因为经过一定时间后,它最终会完全加载。

I believe its because loading an image is not instant, it takes time. 我相信这是因为加载图像不是即时的,需要时间。 Once the image is loaded, then it can be drawn to the canvas 加载图像后,可以将其绘制到画布上

This is needed because the browser needs to "read" and eventually download the image (onload event) to correctly handle the image load. 这是必需的,因为浏览器需要“读取”并最终下载图像(onload事件)以正确处理图像加载。 Using a setInterval to simulate this behaviour could not work, for example loading of a large image on a slow connection... So the best way to do this is: 使用setInterval模拟此行为无法正常工作,例如在慢速连接上加载大图像...因此,执行此操作的最佳方法是:

var img = new Image():
img.src = "image.jpeg";
img.onload = function() {
    // Now you can play with your image.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM