gpt4 book ai didi

javascript - 在浏览器选项卡之间切换时动画不会暂停

转载 作者:行者123 更新时间:2023-11-28 20:10:47 25 4
gpt4 key购买 nike

我是 HTML5 新手,基本上使用与此处找到的类似的代码结构 http://www.html5canvastutorials.com/advanced/html5-canvas-start-and-stop-an-animation/

根据 Paul Irish 的说法,当使用 requestAnimationFrame() 时,在选项卡之间切换时动画会自动暂停

http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/

但在第一个示例中,它不会暂停,而是继续移动,有时当我们切换浏览器选项卡时它会消失。我找到了一个例子,动画确实可以完美地工作。

http://jsfiddle.net/wMkJg/

如何修改代码以使动画在选项卡切换时不再继续?

function animate(lastTime, myRectangle, runAnimation, canvas, context) {

if(runAnimation.value) {
// update
var time = (new Date()).getTime();
var timeDiff = time - lastTime;

// pixels / second
var linearSpeed = 100;
var linearDistEachFrame = linearSpeed * timeDiff / 1000;
var currentX = myRectangle.x;

if(currentX < canvas.width - myRectangle.width - myRectangle.borderWidth / 2) {
var newX = currentX + linearDistEachFrame;
myRectangle.x = newX;
}

// clear
context.clearRect(0, 0, canvas.width, canvas.height);

// draw
drawRect(myRectangle, context);

// request new frame
requestAnimFrame(function() {
animate(time, myRectangle, runAnimation, canvas, context);
});


}
}

最佳答案

rAF 的行为尚未定义。在某些浏览器中,它可能暂停,在其他浏览器中可能降低帧速率等等,但这不是由标准定义的。

您可以使用窗口上的焦点和模糊事件来设置循环可以使用的标志:

var isPaused = false;

window.onblur = function() {
isPaused = true;
}
window.onfocus = function() {
isPaused = false;
animate(...); /// start the loop (or use rAF here too)
}

然后在你的循环中:

requestAnimFrame(function() {
if (!isPaused) animate(time, myRectangle, runAnimation, canvas, context);
});

关于javascript - 在浏览器选项卡之间切换时动画不会暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19939822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com