2011-03-29 94 views
5

使用canvas和javascript嵌套動畫是否可行?例如,一隻蝴蝶拍動翅膀,同時沿着一條路徑移動。使用畫布和javascript嵌套動畫

什麼是創建這種動畫的最佳方式?將有多個相同的蝴蝶在不同的方向移動。

當時我在畫布上繪製蝴蝶形狀,分兩部分,左右兩翼,我將分別進行動畫處理。然後我會沿着一條路徑去動畫整隻蝴蝶。

看起來好像在多個圖形和動畫中會使用很多處理,可以通過使用PNG而不是形狀,甚至是動畫GIF來保存嗎?

任何意見將不勝感激!謝謝!

回答

6

要回答你的第一個問題:是的,他們是可能的。要回答你的第二個問題:一個「最好」的方法是在畫布上下文中使用任意的變換嵌套。

我創建了一個示例,顯示如何在上下文中發出繪圖命令,但不知道當前的轉換是什麼,然後將這些命令包裝在爲結果生成動畫的轉換中。

在這裏看到的結果:http://phrogz.net/tmp/canvas_nested_animations.html

下面是該辦法的一個基本概述:

// Draw a bug with animated legs 
function drawBug(){ 
    ctx.save(); 
    // Issue drawing commands, assuming some 0,0 center and an unrotated bug 
    // Use the current time, or some frame counter, to change how things are drawn 
    ctx.restore(); 
} 

// Move the (animated) bug around 
function drawMovingBug(){ 
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); 

    ctx.save(); 
    // Adjust the bug's location/rotation based on some animation path 
    // and the current time or frame counter. 
    var bugPosition = findCurrentBugPosition(); 
    ctx.rotate(bugPosition.angle); 
    ctx.translate(bugPosition.x,bugPosition.y); 

    // Draw the bug using the new transformation 
    drawBug();   
    ctx.restore(); 
} 
+0

埃,使用內置的轉換堆棧的路要走。 – DuckMaestro 2011-03-30 03:24:05

+0

非常感謝,正是我想知道的!我會給它一個旋轉! :D – iamdarrenhall 2011-03-30 08:13:00

+0

@Progro,我可以先將translate命令放在drawMovingBug方法內,然後將命令放在下一個方向嗎?通過這樣做,會達到與以前相同的效果。 – rajkamal 2012-04-05 09:22:33