leohxj
9/10/2013 - 9:58 AM

播放序列帧动画图片

播放序列帧动画图片

/**
 * 播放序列帧图片
 * @param  {string} elementId         元素id
 * @param  {number} playTime          播放时间/ms
 * @param  {number} totalSpriteHeight 序列帧图片高度/px
 * @param  {number} startFrame        播放开始帧数(0为空白帧)
 * @param  {number} endFrame          播放结束帧数(总帧数+1为空白帧)
 * @return {null}                   没有返回值
 */
function playSpriteAni(elementId, playTime, totalSpriteHeight, startFrame, endFrame) {
    var element = document.getElementById(elementId),
    spriteHeight = element.clientHeight,
    startFrame = (startFrame == 0) || startFrame ? startFrame: 1,
    endFrame = endFrame? endFrame: (totalSpriteHeight/spriteHeight),
    playRate = playTime / (endFrame - startFrame);

    var curFrame = startFrame;
    var transY = -(startFrame-1) * spriteHeight;
    var endtransY = -(endFrame-1) * spriteHeight;

    var sprites = setInterval(function() {
        curFrame++;
        transY -= spriteHeight;

        element.style.backgroundPosition = "0 "+transY+"px";

        if (curFrame == endFrame || document.body.className == 'end') {
            element.style.backgroundPosition = "0 "+ endtransY +"px";
            clearInterval(sprites);
        }

    }, playRate);
}