Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't image show on load, but shows on refresh?

I'm playing with the canvas element in HTML5 and I have noticed a peculiar behavior. On initial load, an image I'm displaying does not show. However, when I refresh the browser, it displays appropriately. I've used IE9 and Chrome. Both behave identically. The JavaScript code looks like this:

window.onload = load;
function load() {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    context.fillRect(0, 0, 640, 400);
    var image = new Image();
    image.src = "Images/smiley.png";
    context.drawImage(image, 50, 50);
}

The rectangle draws correctly both times, it's the smiley that only shows on a browser refresh.

I'm in the process of learning HTML5 and JavaScript. I'm sure I'm just doing something stupid, but I can't figure it out.

like image 457
John Kraft Avatar asked Aug 11 '11 16:08

John Kraft


1 Answers

Images load asynchronously, so only after refresh it loads early enough because it's cached. Normally it isn't loaded yet at the time you call drawImage. Use onload:

var image = new Image();
image.src = "Images/smiley.png";
image.onload = function() {
    context.drawImage(image, 50, 50);
};
like image 88
pimvdb Avatar answered Sep 17 '22 08:09

pimvdb