以有限的帧速率播放requestAnimationFrame [英] requestAnimationFrame at a limited framerate

查看:46
本文介绍了以有限的帧速率播放requestAnimationFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,JS requestAnimationFrame API的使用旨在用于不需要控制帧速率的情况,但我有一个用例,其中必须使用< canvas> 仅以某个fps间隔进行更新,该间隔可能介于1到25之间(即每秒1到25个之间).然后我还能以某种方式仍然有效地使用rAF来获得它提供的优化吗?

As I understand it, usage of the JS requestAnimationFrame API is intended for cases where the framerate isn't in need of being controlled, but I have a use case where it's essential that a <canvas> only updates at a certain fps interval that may be anywhere between 1 and 25 (between 1 and 25 frames per second, that is). Can I then somehow still effectively use rAF to get at the optimizations it offers?

This question has similarities to mine, but the accepted answer there made close to zero sense to me in the context of that question.

对此,我有两种可能的解决方案.第一个涉及使用 while 循环将脚本的执行暂停指定的延迟,然后再从回调内部调用 requestAnimationFrame .在我看到的示例中,它有效地限制了动画的fps,但似乎也减慢了整个选项卡的速度.这实际上仍然是一个好的解决方案吗?正如我在上面链接的问题中所提到的,第二种选择是在 setInterval 中调用 requestAnimationFrame .对我来说,这似乎有些令人费解,但这可能是最好的选择?

I have two possible solutions for this. The first one involves using a while loop to halt the execution of the script for a specified delay before calling requestAnimationFrame from within the callback. In the example where I saw this, it effectively limited the fps of the animation, but it also seemed to slow down the entire tab. Is this still actually a good solution? The second alternative, as mentioned in the question I linked to above, calls requestAnimationFrame within a setInterval. To me that seems a bit convoluted, but it could be that's the best option?

还是有更好的替代方法来实现这一目标?

Or is there a better alternative to accomplish this?

推荐答案

Yoshi的答案可能是解决此问题的最佳代码.但是我仍然会将此答案标记为正确,因为经过一些研究,我基本上发现我的问题是无效的. requestAnimationFrame 的确旨在保持尽可能高的帧频,并且针对需要保持动画一致且流畅的场景进行了优化.

Yoshi's answer is probably the best code solution to this problem. But still I'll mark this answer as correct, because after some research I basically found that my question was invalid. requestAnimationFrame is really meant to keep frame rates as high as possible, and it optimizes for scenarios where animation is meant to be kept consistent and smooth.

值得一提的是,您不需要 requestAnimationFrame 来进行优化(即使rAF被吹捧为性能的增强器),因为浏览器仍在优化< canvas>的常规绘制; .例如,当某个标签页未聚焦时,Chrome浏览器会停止绘制其画布.

Worth noting though is that you don't need requestAnimationFrame to get optimization (even though rAF was touted as a great performance booster) since browsers still optimize regular drawing of a <canvas>. For example, when a tab isn't focused, Chrome for one stops drawing its canvases.

所以我的结论是这个问题无效.希望这对任何想知道与我相似的人有所帮助.

So my conclusion was that this question was invalid. Hope this helps anyone who was wondering something similar to me.

这篇关于以有限的帧速率播放requestAnimationFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆