Calculate FPS in Canvas using requestAnimationFrame

前端 未结 10 2235
滥情空心
滥情空心 2020-11-30 00:31

How could I calculate the FPS of a canvas game application? I\'ve seen some examples, but none of them use requestAnimationFrame, and im not sure how to apply their solution

10条回答
  •  死守一世寂寞
    2020-11-30 01:02

    I was missing an implementation that allows to customize the size of the sample for the averaged FPS value. Here is mine , it has the following features :

    • Accurate : performance.now() based
    • Stabilized : Returned FPS value is an averaged value ( fps.value | fps.tick() )
    • Configurable : FPS samples array size can be customized ( fps.samplesSize )
    • Efficient : Rotatory array for collecting samples (avoids array resizing)

    const fps = {
        sampleSize : 60,    
        value : 0,
        _sample_ : [],
        _index_ : 0,
        _lastTick_: false,
        tick : function(){
            // if is first tick, just set tick timestamp and return
            if( !this._lastTick_ ){
                this._lastTick_ = performance.now();
                return 0;
            }
            // calculate necessary values to obtain current tick FPS
            let now = performance.now();
            let delta = (now - this._lastTick_)/1000;
            let fps = 1/delta;
            // add to fps samples, current tick fps value 
            this._sample_[ this._index_ ] = Math.round(fps);
            
            // iterate samples to obtain the average
            let average = 0;
            for(i=0; i
    --

提交回复
热议问题