javascript - HTML5 Canvas - 暂停时耗时

标签 javascript html loops canvas elapsed

我在增量/耗时方面遇到问题。

当窗口模糊时,循环会正确暂停。

如果您等待几秒钟并单击回窗口(焦点),则耗时将从较高的数字开始,然后重置回 0。

当窗口模糊时,如何阻止耗时增加?这个较高的数字会影响我的动画并使其运行得太快,直到增量再次正确为止。

我已经设置了一个示例循环。你可以在控制台中看到我的意思: Example

if (window.requestAnimationFrame !== undefined) {
    window.requestAnimFrame = (function () {
        'use strict';

        return window.requestAnimationFrame ||
               window.webkitRequestAnimationFrame ||
               window.oRequestAnimationFrame ||
               window.mozRequestAnimationFrame ||
               function (callback) {
                    window.setTimeout(callback, 1000 / 60); //Should be 60 FPS
               };
    }());
}

(function () {
    'use strict';

    var elapsed,
        isPaused = false,
        lastTime = 0,
        loop,
        setElapsed,
        startTime = 0,
        update;

    //Set the elapsed time
    setElapsed = function () {
        startTime = Date.now();
        elapsed = startTime - lastTime; //Calculate the elapsed time since the last frame. Dividing by 1000 turns it to seconds
        lastTime = startTime;
    };

    update = function () {
        //Update the animation etc.
        console.log('animation');
    };

    loop = function () {
        setElapsed();
        update(elapsed);    

        console.log('elapsed: ' + elapsed);

        requestAnimFrame(function () {
            if (isPaused === false) {
                loop();
            } 
        }); //Re-loop constantly using callback window.setTimeout(callback, 1000 / 60); //Should be 60 FPS

    };

    //When the window blurs, pause it
    window.onblur = function () {
        isPaused = true; //Pause the game
    };

    //When the window is in focus, resume it
    window.onfocus = function () {
        isPaused = false;
        loop(); //Re-init the game
    };

    loop();

}());

谢谢

最佳答案

仅当后者非零时,

elapsed 赋值(在 setElapsed 函数内)才应使用 lastTime。否则应设置为 0(表示第一次调用)。

此外,当 onblur 事件发生时,您必须将 lastTime 重置为 0

setElapsed = function () {
    startTime = Date.now();
    elapsed = lastTime? startTime - lastTime : 0;
    lastTime = startTime;
};
...
window.onblur = function () {
    isPaused = true; // Pause the game
    lastTime = 0; // reset lastTime
};

关于javascript - HTML5 Canvas - 暂停时耗时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449793/

相关文章:

android - 如果使用phonegap 和 HTML5 已知 SSID,如何连接到 wifi 网络?

javascript - Onclick 选择特定的 JSON 数据集

菜单中的 C++ 循环

linux - 使用两个输入执行 for 循环

javascript - AngularJS:如何在相同2个 Controller 的多个实例之间提供独立通信?

javascript - 检查 grunt 是否在详细模式下运行

Javascript 长度值与文本区域不一致或不正确

javascript - 如何立即开始 setInterval 循环?

javascript - knockout 启用绑定(bind)不起作用

javascript - ie 7 和 8 中的 html 文本框不检查图像点击