如何平滑我的JavaScript动画?

时间:2013-06-22 00:21:01

标签: javascript canvas

我开始使用以下地址的代码:

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下运行时,动画在高速时似乎仍然有点模糊。我可以做进一步优化吗?

2 个答案:

答案 0 :(得分:2)

我不知道你的意思是模糊,但是20像素的步数会使动画非常粗糙(降低它们以使球不那么模糊/“滑”)。

在任何情况下,如果您想优化此代码,您可以调整以下内容:

//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();

当然可以使用requestAnimationFrame来保持动画与监视器vblank同步(消除混蛋)。

但是把它放在你的主循环中。

以下是这些优化的结果:
http://jsfiddle.net/AbdiasSoftware/XBssp/6/

没有那么多DOM元素和iframe:
http://jsfiddle.net/AbdiasSoftware/XBssp/6/embedded/result/

您无法对DOM更新执行任何操作,因此为了减少重新绘制和事件队列中的其他事件的影响,建议在同一窗口中使用尽可能少的其他元素。如果可能,请使用元素的固定或绝对位置,避免阴影和圆角。

优化方法的来源输出:

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

答案 1 :(得分:2)

jsFiddle Demo

好动画,你非常接近:)

很少有事情。首先,当您制作动画时,通常需要使用小步骤,以便您动画的项目不会起伏不定。其次,确保在小步骤动画时你以高频率进行动画(你已经覆盖了那部分)。第三,当动画对象和碰撞检测是一个问题时,请确保按对象的尺寸偏移边界。

我的演示改变了第一和第三个音符。

var dx=4;
var dy=4;

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

我还使示例中的边界框更清晰。