HTML and CSS Reference
In-Depth Information
img.onload = function() {
ctx.drawImage(img,100,100);
}
img.src = 'images/sprites.png';
}
If you reload the page, you should now see the sprite sheet layered on top of your rectangles. See canvas/
game.js in the chapter code for the complete code. You can see the code first waits for the onload callback
before trying to draw the image onto the context and then sets the src after setting up the callback. The order is
important because Internet Explorer does not trigger the onload callback if the image is cached if you reverse
the order of the two lines. You can see the results—admittedly not pretty—in Figure 1-2 .
Figure 1-2: The spritesheet and drawn rectangles.
This first example uses the simplest drawImage method—one that takes an image and an x and y coordin-
ate and then draws the entire image on the canvas.
Modify the drawImage line to read as follows:
var img = new Image();
img.onload = function() {
ctx.drawImage(img,100,100,200,200);
 
 
 
Search WWH ::




Custom Search