Tyrick
Tyrick

Reputation: 2966

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? And if that is the case, why does it eventually work when nested in a setInterval function?

Upvotes: 0

Views: 2320

Answers (4)

Mimo
Mimo

Reputation: 6075

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 = new Image():
img.src = "image.jpeg";
img.onload = function() {
    // Now you can play with your image.
}

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71939

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.

Upvotes: 1

Brendon John Wildbore
Brendon John Wildbore

Reputation: 600

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

Upvotes: 0

Joseph
Joseph

Reputation: 119877

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 = 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!

Upvotes: 5

Related Questions