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:
- Load the sprite sheet. This is pretty straightforward.
- Use
drawImage
to display just the first sprite from our sprite sheet. If you recall, thedrawImage
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. - Shift the
drawImage
co-ordinates to display the next sprite…and the next sprite…and so on. - Put all of the
drawImage
logic inside arequestAnimationFrame
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 1400+ tech skills courses.