English subtitles

← Loading images - HTML5 Game Development

Get Embed Code
8 Languages

Showing Revision 9 created 05/24/2016 by Udacity Robot.

  1. The bulk of canvas interaction that GRITS uses, is through rendering images to
  2. the canvas. In order to draw an image to the canvas, we first have to load it.
  3. In order to load an image, we need to create a new image object, which in
  4. Javascript, is comprised of three steps. Number 1, is we need to declare the
  5. image object. Number 2, is we need to define its onload function. Then number 3
  6. we need to set the image.source attribute. It's worth noting that as soon as the
  7. source property if this image is set through a value Javascript will kick off
  8. onload function. Because of this, we need to specify the callback function first
  9. before setting the source attribute. Otherwise the image will load the data and
  10. we won't get a callback received.
  11. Now let's take a look at this code. Here is the url of the image that we'd like
  12. you to load. What we want you to do is create a new image object, following the
  13. steps we just mentioned, and set the onload function and source properties for
  14. that image described in the code. Make sure that your onload function is
  15. assigned to this onImageLoad down here, which will actually print out some nice
  16. little message to the console log, letting you know that things have loaded
  17. properly. If you're confused about whether or not your image is loading, don't
  18. forget to check out Chrome's developer tools on the network tab, which will list
  19. whether or not the image has been loaded, and how long it took to do it.