看看 Paul Irish 的requestAnimationFrame
垫片;rAF 比 setInterval 方法有很多优点;主要是它是为做到这一点而构建的,而且它只在浏览器准备好时才请求帧,所以当你的网站在后台时它会暂停发生的事情。当我切换时,我还注意到性能更流畅。
我会说这样的事情应该有效:
var animationHasTriggered = false;
var x = document.getElementById("myCanvas");
var canvas = x.getContext('2d');
var keysDown = {};
var i = 0;
window.addEventListener('load', function()
{
addEventListener("keydown", function(e)
{
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function(e)
{
delete keysDown[e.keyCode];
}, false);
updateAll();
}, false);
function updateAll()
{
if (13 in keysDown || animationHasTriggered)
{
animationHasTriggered = true;
animate();
}
requestAnimationFrame(updateAll);
}
function animate()
{
if (i < 451)
{
canvas.clearRect(0,0,500,500);
canvas.fillStyle="red";
canvas.fillRect(30,i,50,50);
i++;
}
else
{
animationHasTriggered = false;
}
}
(function()
{
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x)
{
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element)
{
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (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);
};
}());