我不知道你的模糊意味着什麼,但是在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
來源
2013-06-22 00:36:25
K3N
在Chrome和Firefox中,我看起來很好。你能解釋一下「模糊」的含義嗎? – Dai
你可以降低@Dai的速度他的意思是你看到它像3個球一樣移動(眼睛幻覺) – copypaste
更具體地說,我指的是重影效果。 @yotam所以這將始終以更高的速度呈現? – deltanovember