2011-12-27 77 views
1

使用JavaScript,我创建了一个对象数组。对象的其中一个属性是Raphael形状。动画拉斐尔JavaScript动画序列

使用$.each(arr, function() {});,我绘制了形状,但我希望它们快速连续fadeIn。所以arr[1].hexagonfadeIn然后arr[2]等等。我已经能够通过将.animate()附加到对象来统一获取它们的所有fadeIn,但我无法弄清楚如何计时JavaScript。

我想更一般地说,有没有使用Raphael或jQuery控制序列和时间的技巧?

回答

1

这不使用拉斐尔或jQuery的,但仅仅是一个在JavaScript中的数组延缓迭代的方式:

var doSomethingWithValue = function(v) { 
    // your call to animate the object, or do anything really. 
    console.log(v); 
} 

var timer = function(a, n) {  
    var delay = 1000; // a second, probably change this to same duration as the fadeIn() 
    doSomethingWithValue(a[n]); // do work 
    n += 1; 
    if (n == a.length) { 
     // if we're at the end, return 
     return; 
    } else { 
     // repeat after delay 
     setTimeout(function() {timer(a, n)}, delay); 
    } 
} 

var arr = [1,2,3]; 
// kick things off starting at first entry 
timer(arr, 0); 

这是否对你的工作?

+0

感谢oli。我会看看这个,看看它是否有意义 – Alex 2011-12-27 18:28:05

+0

我还不确定你是如何做到这一点的,但它确实有效。谢谢! – Alex 2011-12-27 18:46:11

+0

@亚历克斯很高兴它帮助 - 如果您认为需要一些阐述,请让我知道,我可以更新答案。 – oli 2011-12-28 02:14:41

1

尝试使用此代码:

for(var i=0;i < numofObj;i++){

Obj[i].animate({any animate you choose  },1000,function(){ 
Obj[i+1].animate({any animate you choose},1000); 

});

这将使接下来的OBJ动画只有当先前的结束......

2

我需要解决这个问题,但不想依赖setTimeout(当浏览器被最小化时,定时器可能会表现异常,并且通常看起来不正确地使用Raphael)。

因此,受trampolines的启发,我制作了一个动画队列。

一般策略是将匿名函数推入队列中,要求在函数的某个地方,animations.next要么直接调用,要么给动画来触发。

animations = function() { 
    var animationQueue = [] 
    , obj = {} 

    obj.push = function(fn) { 
    animationQueue.push(fn) 
    } 

    obj.next = function() { 
    if (animationQueue.length !== 0) { 
     animationQueue.shift().call() 
    } 
    } 

    return obj 
}() 

然后,你可以做这样的事情了几声:

animations.push(function() { 
    paper.circle(x, y, 2) 
    .attr('fill', '#fff') 
    .animate({r: radius}, animationSpeed, animations.next) 
}) 

最后,在不管它是你正在做到底,叫animations.next()启动链。

+0

我甚至不确定原来的问题是什么,但总能看到有人在一年半后添加答案。时光飞逝。 – Alex 2013-08-05 20:07:25

2

您应该使用raphael Element.animate方法提供的回调。

window.onload = function() { 
el.animate({theAnimation}, 1000, nextAnim); 
} 

function nextAnim(){ 
el2.animate({theAnimation2}, 1000); 
} 

当动画结束时,回调将调用指定的函数。您可以根据需要多次重复此操作。