我是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/
但是在第一个例子中,当我们切换浏览器选项卡时,它不会暂停但会继续移动,有时也会消失。 我找到了一个动画确实可以完美运行的例子。
如何修改代码以便动画不会在制表符开关上继续?
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);
});
}
}
答案 0 :(得分:3)
未定义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);
});