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:
functioneventSheetLoaded(){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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access