我正在使用动画制作一些图像演示
setInterval(function() {
$('.img').css('someprop', randomValue());
}, 2000);
..其中 .img 启用了 css 转换,因此动画。
当我转到另一个选项卡几分钟并返回此选项卡时,动画会疯狂 5-6 秒并立即 catch 所有内容。
有没有办法在选项卡不可见时停止累积未显示的动画?解决这个问题的正确方法是什么?我知道出于性能原因,浏览器会在窗口未呈现时停止动画,但我有没有办法告诉它不要试图 catch 它“错过”的所有内容?
最佳答案
window.requestAnimationFrame
完全按照您的要求进行操作,仅在选项卡处于“事件”(可见)状态时进行动画处理/运行。
参见 MDN page on requestAnimationFrame了解更多详情。
Paul Irish 的示例代码,为后代张贴在这里 (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();
}
关于javascript - 如何检测浏览器选项卡当前是否可见并使用 Javascript 呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23744706/