Javascript帮助,尝试同时为两个不同的精灵制作动画

时间:2015-02-12 20:26:26

标签: javascript jquery animation sprite

我需要一些javascript帮助。我试图在两个单独的div中设置两个具有不同帧速率的精灵动画。

这是我开始的小提琴,我非常困难。

如何将两个div ID合并为一个语句?或者我应该在语句中使用ClassName在两个div上运行吗?

http://jsfiddle.net/akwilinski/3t7d6qbL/1/

<div id="animate" class="animation"></div>
<div id="animate2" class="animation2"></div>

onload = function startAnimation() { 
    var frameHeight = 400; 
    var frames = 27; 
    var frame = 0; 
    var div = document.getElementById("animate"); 
    setInterval(function () { 
        var frameOffset = (++frame % frames) * -frameHeight; 
        div.style.backgroundPosition = "0px " + frameOffset + "px"; 
    }, 100); 

}   

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/f4v1vy7x/5/

我创建了一个Can对象来存储每个can的配置(因此你可以拥有不同的frameHeights,frames和frameRates。

我使用了window.requestAnimationFrame,因为它比setInterval更有效。在每个可用帧上,我根据每个Can的设置帧速率检查是否需要设置动画:

var Can = function( selector, frameHeight, frames, frameRate )
{
    this.domCan = document.getElementById( selector );
    this.frameHeight = frameHeight;
    this.frames = frames;
    this.frameRate = frameRate;
    this.frame = 0;
};

onload = function startAnimation() { 
    var can1 = new Can( 'animate', 400, 27, 20 );
    var can2 = new Can( 'animate2', 400, 27, 100 );

    var cans = [ can1, can2 ]; 

    window.requestAnimationFrame( function() {
        can1.start = can2.start = new Date();
        animate( cans );
    } );
};

var animate = function( cans ) {
    for( var i = 0; i < cans.length; i++ ) {       
        var now = new Date();
        var can = cans[i];
        if( now - can.start >= 1000 / can.frameRate ) {
            can.start = now;
            var frameOffset = (++can.frame % can.frames) * -can.frameHeight; 
            can.domCan.style.backgroundPosition = "0px " + frameOffset + "px";
        }
    }
    window.requestAnimationFrame( function() {
        animate( cans );
    } );
}

答案 1 :(得分:1)

使用您已经开始使用的方法执行此操作的最简单方法是定义2个新变量,1表示第二个div,另一个表示第二个帧计数。然后你可以添加对你的函数的调用。

更新了js:

onload = function startAnimation() { 
var frameHeight = 400; 
var frames = 27; 
var frame = 0; 
var div = document.getElementById("animate"); 
var div2 = document.getElementById("animate2");
setInterval(function () { 
    var frameOffset = (++frame % frames) * -frameHeight; 
    var frameOffset2 = (++frame % frames) * -frameHeight - 10; 
    div.style.backgroundPosition = "0px " + frameOffset + "px"; 
    div2.style.backgroundPosition = "0px " + frameOffset + "px"; 
}, 100);

}   

Fiddle

答案 2 :(得分:0)

你可以这样做:

var div = document.getElementById("animate"); 
var div2 = document.getElementById("animate2");

function anim(div) {
    setInterval(function () { 
        var frameOffset = (++frame % frames) * -frameHeight; 
        div.style.backgroundPosition = "0px " + frameOffset + "px"; 
    }, 100); 
}

anim(div);
anim(div2);

然后您可以传入其他参数,例如frameHeight,frame和frames,以进一步自定义每个动画。

相关问题