简体   繁体   English

检测html5画布是否已暂停

[英]Detect if html5 canvas is paused

i am developing a game with HTML5 canvas and JavaScript. 我正在使用HTML5 canvas和JavaScript开发游戏。

To time the game, i take the system milliseconds from now, subtract the system milliseconds from when the last frame occurred, which leaves me with the milliseconds the last frame took to render. 为了给游戏计时,我从现在开始花费了系统毫秒数,从最后一帧发生时减去系统毫秒数,这使我剩下了最后一帧渲染所花费的毫秒数。

This works fine, but if i open a new tab in Firefox, the canvas seems to get paused by Firefox, and when i come back, the current system time is many seconds later then the system time the last frame occurred and everything jumps, because its movement is relative to the last frame time. 效果很好,但是如果我在Firefox中打开新标签页,Firefox似乎会暂停画布,而当我返回时,当前系统时间要晚几秒钟,然后系统时间才会出现最后一帧,并且所有内容都会跳跃,因为其移动是相对于最后一帧时间。

I need some way to either detect, that the canvas is not running at the moment, or that Firefox (and of course other browsers) has switchted to another tab, so i can pause my game, and when returning, update the 'last frame time' to prevent jumps. 我需要某种方法来检测画布当前是否未运行,或者Firefox(当然还有其他浏览器)已切换到另一个选项卡,以便我可以暂停游戏,并在返回时更新“最后一帧”。时间以防止跳跃。

Any ideas? 有任何想法吗?

您还可以使用window onblur事件检测选项卡何时更改。

That's just one cause of clock jump. 那只是时钟跳动的原因之一。 You're still vulnerable to forced process sleep, high system load, computer sleep mode, hibernation, and a dozen other scenarios. 您仍然容易遭受强制进程睡眠,高系统负载,计算机睡眠模式,休眠以及其他十几种情况。

You need to cap the time delta. 您需要设置时间增量。 In my projects (hobby games), I've found 80ms to be a functional maximum. 在我的项目(业余游戏)中,我发现80ms是最大功能。

(Also, collision detection is much harder without a cap.) (此外,如果没有上限,则碰撞检测要困难得多。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM