【问题标题】:Animation does not pause when switched between browser tabs在浏览器选项卡之间切换时动画不会暂停
【发布时间】:2013-11-13 05:12:30
【问题描述】:

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


        }
}

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

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

    【讨论】:

    • 谢谢你,这是一个已知问题还是示例中给出的逻辑错误?
    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2012-08-01
    • 2017-03-21
    • 2014-01-06
    • 2014-10-20
    相关资源
    最近更新 更多