总是从 Paul Irish 的 requestAnimationFrame 跨浏览器 shim 开始
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
然后只需编写一个动画函数:
- 更新驱动动画的变量(位置、速度、颜色变化等)
- 使用画布的上下文绘制当前帧
- 通过重新调用 requestAnimFrame 使动画在下一帧保持活动状态
这是示例骨架代码:
function animate() {
// update animation variables
X+=20;
Velocity +=10;
// clear the canvas and draw the current frame
// based on the variables you just updated
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.rect(x,y,75,50);
// request new frame to keep the animation going
requestAnimFrame( animate );
}
以下是如何降低动画的速度(如 FPS——但不是):
// set a countdown "throttle" that will slow animate() down by 4X
var notEveryTime=3;
function animate() {
// if notEveryTime hasn't counted down to 0
// then just don't animate yet
if(--notEveryTime>0){ return; };
// update animation variables
X+=20;
Velocity +=10;
// clear the canvas and draw the current frame
// based on the variables you just updated
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.rect(x,y,75,50);
// request new frame to keep the animation going
requestAnimFrame( animate );
// reset notEveryTime
notEveryTime=3;
}
并阅读 Anreas 的好建议:http : //paulirish.com/2011/requestanimationframe-for-smart-animating/