2015-04-04 83 views
0

我遇到了增量/經過時間的問題。HTML5帆布 - 暫停時間已過去

當窗口模糊時,循環會正確暫停。

如果您等待幾秒鐘,然後單擊返回到窗口(焦點),所經過的時間開始於一個較大的數字,然後重置回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(); 

}()); 

感謝

回答

1

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 
}; 
+0

這是一個很好的解決方案,它的工作原理。非常感謝。我很感激。 – Paddy 2015-04-04 18:58:47

+0

@Paddy如果它解決了你的問題,你也可以使用這個答案 – hindmost 2015-04-04 19:09:49

+0

你的答案的改進版本將使用傳遞給requestAnimationFrame的timestamp參數來實現已用時間。 ;-) – markE 2015-04-04 19:18:41