我正在制作一些图像演示动画,使用
setInterval(function() {
$('.img').css('someprop', randomValue());
}, 2000);..where .img启用了css过渡,因此也启用了动画。
当我转到另一个选项卡几分钟后回到这个选项卡时,动画会疯狂地持续5-6秒,并立即赶上所有内容。
有没有办法在选项卡不可见时停止未显示动画的累积?解决这个问题的正确方法是什么?我知道浏览器会在窗口没有渲染时停止动画,但是有没有办法让我告诉它不要去追赶它“错过的”所有东西呢?
发布于 2014-05-20 02:34:05
window.requestAnimationFrame完全按照您的要求进行操作,仅在选项卡处于“活动”状态(可见)时进行动画/运行。
有关更多详细信息,请参阅MDN page on requestAnimationFrame。
保罗·爱尔兰编写的示例代码,在此发布给后人(here's a link to his explanation page)
// requestAnim shim layer by Paul Irish
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
// example code from mr doob : http://mrdoob.com/lab/javascript/requestanimationframe/
var canvas, context, toggle;
init();
animate();
function init() {
canvas = document.createElement( 'canvas' );
canvas.width = 512;
canvas.height = 512;
context = canvas.getContext( '2d' );
document.body.appendChild( canvas );
}
function animate() {
requestAnimFrame( animate );
draw();
}
function draw() {
var time = new Date().getTime() * 0.002;
var x = Math.sin( time ) * 192 + 256;
var y = Math.cos( time * 0.9 ) * 192 + 256;
toggle = !toggle;
context.fillStyle = toggle ? 'rgb(200,200,20)' : 'rgb(20,20,200)';
context.beginPath();
context.arc( x, y, 10, 0, Math.PI * 2, true );
context.closePath();
context.fill();
}https://stackoverflow.com/questions/23744706
复制相似问题