Easing a sprite animation in JS

621 views Asked by At

I've got my sprite sheet animating in vanilla JS by shifting the background-position at a fixed FPS, using requestAnimationFrame and setTimeout to set the framerate.

Ultimately I'd like to animate it with an easing curve, such as QuadInOut, or better still a custom curve. Most of the frameworks I've looked at have their easing built into their tween function, and not for animating a sprite sheet.

Can anyone suggest a JS framework that might help? GSAP or Enchant perhaps? Or alternatively explain the logic behind updating the fps via an easing curve?

Here's my 'linear' animation at the moment:

var theSprite= $('.sprite');
var timesRun = 0;
var shift = 0;
var fps = 20;        

var anim = function() {

    setTimeout(function() {

        shift -= 520;
        theSprite.css('background-position', shift +'px 0');

        timesRun += 1;

        if(timesRun === 19) {
            timesRun = 0;
            shift = 0;
        }


        animAgain = requestAnimationFrame(anim);

    }, 1000 / fps);
}

anim();
2

There are 2 answers

1
Frederik.L On

I think you would definitely enjoy KineticJS. It works like a charm and is designed for what you are trying to do.

See: HTML5 Canvas KineticJS Sprite Tutorial

0
Derek O Brien On

Enchant.js has a few different ways sprite animation. if you look at the enchant.timeline class here http://wise9.github.io/enchant.js/doc/plugins/en/symbols/enchant.Timeline.html it has a few different functions for easing sprites in different ways.