开发者

Increase FPS in animation in javascript

I'm doing an animation using javascript:

 function animate(){
    window.setTimeout(function(){

        //Do a new frame and recall this function till the animation is fi开发者_如何学Gonished

    }, 1000/FPS);//FPS Default 15 approximately 60FPS
 }
 animate();

I'm wondering how I can increase the FPS without losing the quality? Using the already built-in css3 is not an option because I have custom-built an animation.


A couple of suggestions:

  1. Do not rely on setTimeout, setInterval, or any other built-in utility for scheduling a function invocation to provide a high degree of accuracy or precision, particularly when you are executing custom rendering code.

  2. Decouple the ideas of frame and time in your mind. Yes an animation is internally a series of frames, but the end result is something that's supposed to appear to move fluidly through time. So instead of drawing frame 'n', scheduling a timeout for 1000/FPS and then assuming that "it's time to draw frame 'n + 1' now", try drawing frame 'n', scheduling a timeout for some very short interval (like 10 ms), and then (when the timeout fires) measuring the actual amount of time elapsed between when the animation started and the current point in time. Then use your elapsed time to decide what frame should be showing at this exact moment in time (which may still be 'n', or 'n + 1', or maybe even 'n + 3' if your rendering code takes very long to execute), and render that frame. Trust me, you'll get smoother, more consistent results that way.

In terms of how to improve the framerate and/or rendering quality once you have a reasonably set-up rendering loop, that is all about optimizing your //Do a new frame code as much as you possibly can.


It's worth knowing a couple of things: FPS above 60 is usually meaningless, as browsers struggle to repaint the screen any quicker than that. And setTimeout is inconsistent. Just because you tell a script to run every 50ms (for example), doesn't mean it will. There's typically a variance of up to 15ms in either direction.

Decent strategies for improving quality would be making use of some sort of easing calculation, syncing the FPS with the browser repaint cycle - some information about this here - and making use of motion blur, etc, to smooth the effect.

Check out http://weblogs.mozillazine.org/roc/archives/2010/11/measuring_fps.html for some Firefox-specific insights.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜