It's Coding Time!

Now that we’ve seen an English version of how a sprite animation works, it’s time to convert all of that into JavaScript. Our code is going to follow these four basic steps:

  1. Load the sprite sheet. This is pretty straightforward.
  2. Use drawImage to display just the first sprite from our sprite sheet. If you recall, the drawImage method allows you to optionally specify the exact co-ordinates and dimension of the image you want to display instead of displaying the whole thing.
  3. Shift the drawImage co-ordinates to display the next sprite…and the next sprite…and so on.
  4. Put all of the drawImage logic inside a requestAnimationFrame loop to create our animation.

We are going to add some code that does all four of these steps next! Make sure you have our usual HTML document setup with a canvas element whose id value is myCanvas. This is the same type of document we’ve been starting off from forever, but for your reference, the content look as follows:

Get hands-on with 1200+ tech skills courses.