What would happen if I try use drawImage() for an image which not yet fully loaded?
If I pass the reference to an image to drawImage
API开发者_如何学运维 of HTML canvas
, but the image is still loading, then what would happen? Will get an exception, or the API will go ahead with the partial data, or the API will block till the image is loaded?
The canvas spec dictates that nothing shall be drawn, even if it is 99% loaded. It does not throw an error.
So if you do:
var img = new Image();
img.src = 'http://placekitten.com/300/300';
// Might occur before the image is done loading (bad!)
ctx.drawImage(img, 0, 0);
This is why most people do something similar to:
var img = new Image();
img.onload = function() {
// Will occur only once the image is done loading
ctx.drawImage(img, 0, 0);
}
img.src = 'http://placekitten.com/300/300';
To ensure that the image will get drawn.
The spec says that nothing is to be drawn.
If the first argument isn't an img, canvas, or video element, throws a TYPE_MISMATCH_ERR exception. If the image has no image data, throws an INVALID_STATE_ERR exception. If the one of the source rectangle dimensions is zero, throws an INDEX_SIZE_ERR exception. If the image isn't yet fully decoded, then nothing is drawn.
I tried it just for the hell of it. You can see the results here.
I basically used PHP to slow down the image loading.
slowimage.php
<?php
sleep(3);
header('Content-type: image/png');
echo file_get_contents('stackoverflow-logo-300.png');
?>
index.html
<canvas id="canvas" width="512" height="512">
<script>
var img = new Image();
img.onload = function() {
alert("image loaded");
};
img.src = "slowimage.php";
var ctx = document.getElementById("canvas").getContext("2d");
ctx.drawImage(img, 0, 0);
</script>
As has been established, and as you can see, nothing is drawn.
I once stumbled upon this; the problem was that I didn't see anything drawn because I wasn't using img.onload
.
You can confirm it: http://jsfiddle.net/pimvdb/eGjak/100/. It will most probably not show at first, but will after reload because of the cache.
The best practice is to use onload
at all times.
The API will draw nothing onto the canvas. Unless you are using a loop that redraws the canvas with the image included on it the user will never see the image. The normal practice is to use onload with images for canvas - all browsers that support canvas support img.onload. In a loop situation you may be able to get away with adding images on the fly but know that until they are downloaded they are not seen.
精彩评论