Preloading Images

Before an image can be called in code, we must ensure that it has properly loaded and is ready to be used. We do this by creating an event listener to fire off when the load event on the image occurs:

spaceShip.addEventListener('load', eventSheetLoaded , false);

When the image is fully loaded, the eventSheetLoaded() function will fire off. Inside this function, we will then call drawScreen(), as we have in the previous chapters:

function eventSheetLoaded() {
   drawScreen();
}

Note

In practice, we would not create a separate event listener function for each loaded image. This code example works fine if your application contains only a single image. In Chapter 9, we will build a game with multiple image files (and sounds) and use a single listener function for all loaded resources.

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.