DEV Community

Animating Sprite Sheets With JavaScript

Martin Himmel on July 01, 2018

Let's look at animating a sprite sheet, on an HTML5 canvas, using JavaScript. A Little Setup First, let's create the canvas element. ...
Collapse
 
adamthewizard profile image
Adam

Yes, Marty!

I literally started building something yesterday and needed to use sprite sheets but I got a bit stuck and just decided to animate a round div instead! Lol

This is literally gold for me right now, man! Thanks for writing this up!

If I get this finished I'll show you the final product!

Thanks again! ✌🏻😁

Collapse
 
martyhimmel profile image
Martin Himmel

Glad I could help! I look forward to seeing your project!

Collapse
 
deedeessay profile image
deedee resists!

Great tut Martin. Am just learning.
Can I ask... how to stop the looping? Say you want the animation to complete only one cycle?

Collapse
 
martyhimmel profile image
Martin Himmel

requestAnimationFrame returns a long integer. If you assign that to a variable, you can then call cancelAnimationFrame(id) once the required condition is met to stop the cycle.

Using the step function as an example, something like this:

let animationFrameId;

function step() {
    if (animationFrameId && conditionToStopCycle) {
        window.cancelAnimationFrame(animationFrameId);
        return;
    }
    // rest of the code
    animationFrameId = window.requestAnimationFrame(step);
}
Enter fullscreen mode Exit fullscreen mode

Another way could be to return early to break out of the step function. If only one cycle is needed, once the counter reaches the end of the array, return before calling the next requestAnimationFrame (instead of reseting the counter to 0 and continuing).

Here are the MDN pages for requestAnimationFrame and cancelAnimationFrame.

Collapse
 
deedeessay profile image
deedee resists!

Thank you... I really appreciate your help.

Collapse
 
sammygutierrez335 profile image
Sammy Gutierrez

Thank you so much for this tutorial. It was my first exposure to making sprite animation but your walk through/examples was very clear. :)

Collapse
 
lexlohr profile image
Alex Lohr

CSS3 animations using steps(n) will work in most modern browsers, too.

Collapse
 
martyhimmel profile image
Martin Himmel

Good to know. I haven't done much with CSS animations yet. Thanks!

Collapse
 
geraldosantos profile image
Geraldo dos Santos

This is incredible! Thanks for the super clear and thorough explanation.

Collapse
 
salvatore_ profile image
Salvatore_

Nice thanks

Collapse
 
mugammad profile image
Mugammad

Thank you so much mr Himmel.

Collapse
 
gmartigny profile image
Guillaume Martigny

Nice article, I also cover this topic if someone want another point of view.