0

我是 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);
                  });


        }
}
4

1 回答 1

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);
});
于 2013-11-12T21:12:30.753 回答