Search code examples
javascriptjquerycssanimationspritely

jQuery Sprites with Spritely


After 2 solid days of being stuck on one problem, I finally found a MUCH simpler way of making an animation from several frames... it's called Spritely.

What I have so far

var play_frames = 23;

$('#door_hov').hover(
    function() {
        $('#door').sprite({
            fps: 24,
            no_of_frames: 23,
            play_frames: play_frames
        });
        play_frames = 22;
    },
    function() {
        $('#door').sprite({
            fps: 24,
            no_of_frames: 23,
            play_frames: 22,
            rewind: true
        });
    }
);​
  • When you mouseover, it starts the animation.

  • When you mouseout, it rewinds the animation.

The problem

If you mouseout before the animation finishes, or mouseover before the rewind finishes, it winds up going too far and being out of sync.

What I want to do

  • On mouseout, rewind ONLY to frame 1 and stop there.
  • On mouseover, play ONLY until the last frame and stop there.
  • If I mouseout (during animation) at frame x, I want it to rewind from frame x to frame 1.
  • If I mouseover (during rewind) at frame x, I want it to play from frame x to the last frame.

Thanks in advance!


Solution

  • If I understood you right, then you want something like this. Note: You might be able to shorten the code much more with the help of play_frames.

    var iFrames = 23,
        iFps = 24,
        bRewind = false,
        iStartFrame = -1,
        bAnimating = false,
        stopAndRewind = function(oAnim) {
            iStartFrame = ~iStartFrame ? -1 : iFrames - 2;
            bRewind = !bRewind;
            bAnimating = false;
            oAnim.spStop();
        };
    $("#door").on("mouseenter mouseleave", function() {
        var iCurFrame = iStartFrame;
        if ($._spritely.instances && $._spritely.instances[$(this).prop("id")])
        {
            if (bAnimating)
            {
                iCurFrame = $(this).spGet("current_frame");
                stopAndRewind($(this));
            }
            $(this).destroy();
        }
        bAnimating = true;
        $(this).sprite({
            fps: iFps,
            no_of_frames: iFrames,
            start_at_frame: iCurFrame,
            rewind: bRewind,
            on_frame: (function() {
                var o = {},
                    i = 1;
                if (!bRewind)
                {
                    i = iFrames - 2;
                }
                o[i] = stopAndRewind;
                return o;
            })()
        });
    });​