2013-06-22 56 views
2

我開始的代碼,地址如下:如何平滑我的JavaScript動畫?

http://demos.sixrevisions.com/2010/09/11/demo.html

我更新它使用requestAnimFrame如下:

window.requestAnimFrame = (function(){ 
    return window.requestAnimationFrame  || 
     window.webkitRequestAnimationFrame || 
     window.mozRequestAnimationFrame || 
     function(callback){ 
      window.setTimeout(callback, 1000/60); 
     }; 
})(); 

演示,請訪問:

http://jsfiddle.net/XBssp/1/

在我眼中運行Chrome瀏覽器的動畫似乎仍然是在更高的速度下模糊不清。我可以進一步優化什麼?

+0

在Chrome和Firefox中,我看起來很好。你能解釋一下「模糊」的含義嗎? – Dai

+1

你可以降低@Dai的速度他的意思是你看到它像3個球一樣移動(眼睛幻覺) – copypaste

+0

更具體地說,我指的是重影效果。 @yotam所以這將始終以更高的速度呈現? – deltanovember

回答

2

jsFiddle Demo

漂亮的動畫,你是非常接近:)

一些事情。首先,當你製作動畫時,你通常需要一些小步驟,這樣你動畫的項目就不會起伏不定。其次,確保當以小的步幅進行動畫製作時,您可以高頻率進行動畫製作(您可以覆蓋該部分)。第三,當動畫對象和碰撞檢測是一個問題時,確保你用對象的尺寸來抵消邊界。

我的演示已經改變了第一個和第三個音符。

var dx=4; 
var dy=4; 

if(x < 20 || x > 280) 
dx=-dx; 
if(y < 20 || y > 280) 

我也做了邊框的例子更加清晰。

2

我不知道你的模糊意味着什麼,但是在20像素的步驟會使動畫變得非常粗糙(降低它們以減少模糊/「skippy」)。

在任何情況下,如果要優化這個代碼,你可以調整以下的事情:

//put this outside the loop, no need to get it everytime 
context= myCanvas.getContext('2d'); 

//record previous position and size and only clear that area 
//instead of the complete canvas for each time 
context.clearRect(0,0,300,300); 

//pre-render this object to an off-screen canvas and use 
//drawImage(osCanvas, x, y) instead 
context.beginPath(); 
context.fillStyle="#0000ff"; 
context.arc(x,y,20,0,Math.PI*2,true); 
context.closePath(); 
context.fill(); 

當然和使用​​時可用以保持動畫同步與顯示器VBLANK(消除抽搐)。

但把它放在你的主循環。

下面是這些優化的結果:
http://jsfiddle.net/AbdiasSoftware/XBssp/6/

沒有這麼多的DOM元素和iframe:
http://jsfiddle.net/AbdiasSoftware/XBssp/6/embedded/result/

約DOM更新,因此減少重繪等的影響,你不能做任何事情事件隊列中的事件,建議在同一個窗口中包含儘可能少的其他元素。儘可能爲元素使用固定或絕對位置,避免陰影和圓角邊框。 optmized辦法

源型輸出:

function draw() { 
    //here we only clear last draw and draw the cached ball 
    context.clearRect(oldX - 2, oldY -2 ,dia +4,dia +4); 
    context.drawImage(canvas,x, y); 

    oldX = x; //store the current x/y as old x/y for next loop 
    oldY = y; 

    if(x<0 || x>300) dx=-dx; 
    if(y<0 || y>300) dy=-dy; 

    x+=dx; 
    y+=dy; 
    requestAnimationFrame(draw); 
} 

//function to create cached ball 
function createBall() { 
    canvas = document.createElement('canvas'); 
    canvas.width = dia; 
    canvas.height = dia; 
    var ctx = canvas.getContext('2d'); 

    ctx.beginPath(); 
    ctx.fillStyle="#0000ff"; 
    ctx.arc(rad,rad,rad,0,Math.PI*2,true); 
    ctx.fill(); 
} 

createBall(); //create ball 
draw();  //start anim