我在增量/耗时方面遇到问题。
当窗口模糊时,循环会正确暂停。
如果您等待几秒钟并单击回窗口(焦点),则耗时将从较高的数字开始,然后重置回 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/