Using Drawimage In Html5
Solution 1:
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.
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 = newImage(); //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!
Solution 2:
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. And it works with setInterval because, after a certain amount of time, it eventually gets fully loaded.
Solution 3:
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
Solution 4:
This is needed because the browser needs to "read" and eventually download the image (onload event) to correctly handle the image load. 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:
var img = newImage():
img.src = "image.jpeg";
img.onload = function() {
// Now you can play with your image.
}
Post a Comment for "Using Drawimage In Html5"