How to implement renderer with respect to CPU capabilities

夙愿已清 提交于 2020-01-04 01:44:52

问题


I was wondering what is the best way to implement a renderer in JavaScript. It's not the content part of the rendering that's really important here - I would rather like to hear when and how to effectively run the renderer code.

Currently, I have window.setInterval(renderFunc, 1000 / 20), which will just render a frame each 50 ms (i.e., fps = 20).

The point is that faster computers won't render more frames, moreover slower computers will not be able to catch up with 20 fps, so the function is called more than the computer might be able to handle.

I was thinking of a while(true) loop, but this uses 100% CPU and will freeze the computer itself - so actually my game (the renderer is of my 3D game) won't be playable anymore at all since you cannot click on buttons anymore.

What is the most efficient option in this scenario, or is there a better method that has not come to my mind?

Thanks in advance.


回答1:


You could time how long a frame render takes, and adjust frame spacing to achieve an acceptable load. E.g., if your current frame took 5ms to render, and you want 50% load, wait 5ms before the next frame. You'll want to put some sanity checks on it, and also probably use times from the last several frames.




回答2:


There's a feature that is made specifically for animation, called window.requestAnimationFrame. This means that the browsers chooses when to call your animation function instead of you hardcoding intervals. Lots of benefits from using it:

  • Faster computers will get higher frame rates
  • Windows/tabs that aren't visible are updated much less often
  • Varying frame rate depending on CPU usage

This article explains how to use it in a cross browser fashion: http://paulirish.com/2011/requestanimationframe-for-smart-animating/

The article also links to http://jsfiddle.net/paul/XQpzU/2/




回答3:


Look into trying the while(true) loop inside of a web worker thread. This should prevent the browser from locking up. Note that you can't directly manipulate a <canvas> or any other part of the DOM from within the worker thread.

https://developer.mozilla.org/En/Using_web_workers




回答4:


"setInterval() will pass the number of milliseconds late the callback was called" -- https://developer.mozilla.org/en/window.setInterval

You could use this to dynamically adjust your interval time.

N.B. MDC docs are for Javascript as implemented by Mozilla, not ECMA Script or other implementations. You should check if this works in other browsers.



来源:https://stackoverflow.com/questions/5121326/how-to-implement-renderer-with-respect-to-cpu-capabilities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!