requestAnimationFrame与setInterval,setTimeout

时间:2024-01-19 17:05:02

自打学习canvas动画以来,都说requestAnimationFrame好,就一直用,也没觉得有什么太过于特殊的地方,直到刚才,在写完前面的"小球碰撞墙壁----干掉误差"之后,,突然想去看看如果这里改回setInterval,会是个什么样,差距究竟有多大?

结果....一看吓一跳,差距太大了,说难听点,setInterval...简直像屎一样

具体结果,只需要将前面那篇里面的gamleLoop方法和该方法前面的那句gameLoop()  替换成下面的代码,一看就知道了.

function gameLoop(){

    ctx.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
ball.draw(ctx);
ball.update();
} setInterval(gameLoop,30)

不亲自做实践,就没法取得进步,果真是这样.

requestAnimationFrame简易可兼容的方法

window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
return window.setTimeout(callback, 1000 / 60);
};
})();

较为完整的方法

(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || // Webkit中此取消方法的名字变了
window[vendors[x] + 'CancelRequestAnimationFrame'];
} if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}());