Robert
Robert

Reputation: 1638

Javascript Event Handler Image Object

I need help understand the following javascript. How is it that the the image is being drawn on the context before the source is being set on the image? I'm reading an HTML 5 game development book and this is sample book from the book.

var ctx = canvas.getContext && canvas.getContext("2d");
var img = new Image();
img.onload = function() {
ctx.drawImage(img,100,100);
}
img.src = 'images/sprites.png';

Upvotes: 0

Views: 2318

Answers (2)

Aadit M Shah
Aadit M Shah

Reputation: 74204

The image is not being drawn before the src is set on the image. The image is being drawn inside the img.onload event handler function which is called only once the image loads:

image.onload = function () {
    context.drawImage(image, 100, 100);
};

In plain English this reads as "draw the image only once it loads."

What's happening here?

var context = canvas.getContext("2d");  // get the 2d context

var image = new Image;                  // create a new image object

image.onload = function () {            // once the image loads
    context.drawImage(image, 100, 100); // draw the image
};

image.src = "images/sprites.png";       // load the image

You may define the onload function either before or after setting image.src. It doesn't really matter. However most people like to define it before.

Upvotes: 2

Amit Ray
Amit Ray

Reputation: 3485

if you see its img.onload which means the function works once the image is loaded on page. so the source is set first and than the image is drawn.

Upvotes: 0

Related Questions