2011-12-27 82 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); 
} 

當動畫結束時,回調將調用指定的函數。您可以根據需要多次重複此操作。