我如何平滑我的JavaScript动画

How can I smooth out my JavaScript animations?

本文关键字:我的 JavaScript 动画 平滑 何平滑      更新时间:2023-09-26

我从以下地址的代码开始:

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

jsFiddle Demo

不错的动画,你很接近:)

一些事情。首先,当你制作动画时,你通常希望有小的步骤,这样你制作动画的项目就不会起伏不定。其次,确保当你以小步骤制作动画时,你使用高频率(你已经覆盖了这部分内容)。第三,当动画对象和碰撞检测是一个问题时,确保你用对象的尺寸抵消了边界。

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

var dx=4;
var dy=4;

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

我还使边界框更清晰的例子

我不知道你说的模糊是什么意思,但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