使用requestAnimationFrame在Canvas中计算FPS

问题描述 投票:30回答:9

我怎么能计算画布游戏应用程序的FPS?我已经看过一些例子,但没有一个使用requestAnimationFrame,我不知道如何在那里应用他们的解决方案。这是我的代码:

(function(window, document, undefined){

    var canvas       = document.getElementById("mycanvas"),
        context      = canvas.getContext("2d"),
        width        = canvas.width,
        height       = canvas.height,
        fps          = 0,
        game_running = true,
        show_fps     = true;

    function showFPS(){
        context.fillStyle = "Black";
        context.font      = "normal 16pt Arial";

        context.fillText(fps + " fps", 10, 26);
    }
    function gameLoop(){

        //Clear screen
        context.clearRect(0, 0, width, height);

        if (show_fps) showFPS();

        if (game_running) requestAnimationFrame(gameLoop);

    }
    
    gameLoop();

}(this, this.document))
canvas{
    border: 3px solid #fd3300;
}
<canvas id="mycanvas" width="300" height="150"></canvas>

顺便说一句,有没有我可以添加的库来监督性能?

javascript canvas frame-rate requestanimationframe
9个回答
23
投票

不要使用new Date()

此API有几个缺陷,仅对获取当前日期+时间有用。不适用于测量时间跨度。

Date-API使用操作系统的内部时钟,该时钟不断更新并与NTP时间服务器同步。这意味着,该时钟的速度/频率有时更快,有时比实际时间更慢 - 因此不能用于测量持续时间和帧速率。

如果有人更改了系统时间(手动或由于夏令时),如果一帧突然需要一小时,您至少可以看到问题。或者是负面时间。但如果系统时钟与世界时间同步快20%,则几乎不可能检测到。

此外,Date-API非常不精确 - 通常远小于1ms。这使得它对于帧速率测量尤其无用,其中一个60Hz帧需要~17ms。

相反,使用performance.now()

Performance API专门针对此类用例而制作,可以与new Date()等效使用。只需采取其中一个答案,用new Date()取代performance.now(),你就可以开始了。

资料来源:

与Date.now()不同,Performance.now()返回的值总是以恒定速率增加,与系统时钟无关(可以手动调整或由NTP等软件调整)。否则,performance.timing.navigationStart + performance.now()将大致等于Date.now()。

https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

对于Windows:

[时间服务]调整本地时钟速率,使其收敛到正确的时间。如果本地时钟和[准确时间样本]之间的时间差太大而无法通过调整本地时钟速率来校正,则时间服务将本地时钟设置为正确的时间。

https://technet.microsoft.com/en-us/library/cc773013(v=ws.10).aspx


26
投票

您可以跟踪上次调用requestAnimFrame的时间。

var lastCalledTime;
var fps;

function requestAnimFrame() {

  if(!lastCalledTime) {
     lastCalledTime = Date.now();
     fps = 0;
     return;
  }
  delta = (Date.now() - lastCalledTime)/1000;
  lastCalledTime = Date.now();
  fps = 1/delta;
} 

http://jsfiddle.net/vZP3u/


17
投票

Chrome有一个内置的fps计数器:https://developer.chrome.com/devtools/docs/rendering-settings

enter image description here

只需打开开发控制台(F12),打开抽屉(Esc),然后添加“渲染”选项卡。

在这里,您可以激活FPS-Meter叠加层以查看当前帧速率(包括漂亮的图形)以及GPU内存消耗。

跨浏览器解决方案:您可以使用JavaScript库stat.js:https://github.com/mrdoob/stats.js/获得类似的叠加层

enter image description here

它还为帧速率(包括图形)提供了很好的叠加,并且非常易于使用。

比较stats.js和chrome dev工具的结果时,两者都显示完全相同的测量值。所以你可以相信那个库实际上做了正确的事情。


8
投票

我有一个不同的方法,因为如果你计算FPS,你会在返回数字时得到这个闪烁。我决定计算每一帧并每秒返回一次

window.countFPS = (function () {
  var lastLoop = (new Date()).getMilliseconds();
  var count = 1;
  var fps = 0;

  return function () {
    var currentLoop = (new Date()).getMilliseconds();
    if (lastLoop > currentLoop) {
      fps = count;
      count = 1;
    } else {
      count += 1;
    }
    lastLoop = currentLoop;
    return fps;
  };
}());

requestAnimationFrame(function () {
  console.log(countFPS());
});

jsfiddle


3
投票

只需检查AFR回调之间的时间差。 AFR已将时间作为回调的参数传递。我更新了你的小提琴来表明它:http://jsfiddle.net/WCKhH/1/


3
投票

只是一个概念证明。非常简单的代码。我们所做的只是设置每秒帧数和每帧之间的间隔。在绘图功能中,我们从当前时间中扣除最后一帧的执行时间,以检查自上一帧起经过的时间是否大于我们的间隔(基于fps)。如果条件的计算结果为true,我们将设置当前帧的时间,该时间将是下一个绘图调用中的“最后一帧执行时间”。

var GameLoop = function(fn, fps){
    var now;
    var delta;
    var interval;
    var then = new Date().getTime();

    var frames;
    var oldtime = 0;

    return (function loop(time){
        requestAnimationFrame(loop);

        interval = 1000 / (this.fps || fps || 60);
        now = new Date().getTime();
        delta = now - then;

        if (delta > interval) {
            // update time stuffs
            then = now - (delta % interval);

            // calculate the frames per second
            frames = 1000 / (time - oldtime)
            oldtime = time;

            // call the fn
            // and pass current fps to it
            fn(frames);
        }
    }(0));
};

用法:

var set;
document.onclick = function(){
    set = true;
};

GameLoop(function(fps){
    if(set) this.fps = 30;
    console.log(fps);
}, 5);

http://jsfiddle.net/ARTsinn/rPAeN/


3
投票

这是另一个解决方案:

var times = [];
var fps;

function refreshLoop() {
  window.requestAnimationFrame(function() {
    const now = performance.now();
    while (times.length > 0 && times[0] <= now - 1000) {
      times.shift();
    }
    times.push(now);
    fps = times.length;
    refreshLoop();
  });
}

refreshLoop();

这通过以下方式改进了其他一些方面:

  • performance.now()用于Date.now()以提高精度(as covered in this answer
  • FPS是在最后一秒内测量的,所以数字不会如此不规律地跳跃,特别是对于具有单个长帧的应用。

我更详细地写了关于这个解决方案的on my website


3
投票

实际上,没有一个答案对我来说足够了。这是一个更好的解决方案:

  • 使用性能。现在()
  • 计算每秒的实际平均fps
  • 每秒平均值和小数位数是可配置的

码:

// Options
const outputEl         = document.getElementById('fps-output');
const decimalPlaces    = 2;
const updateEachSecond = 1;

// Cache values
const decimalPlacesRatio = Math.pow(10, decimalPlaces);
let timeMeasurements     = [];

// Final output
let fps = 0;

const tick = function() {
  timeMeasurements.push(performance.now());

  const msPassed = timeMeasurements[timeMeasurements.length - 1] - timeMeasurements[0];

  if (msPassed >= updateEachSecond * 1000) {
    fps = Math.round(timeMeasurements.length / msPassed * 1000 * decimalPlacesRatio) / decimalPlacesRatio;
    timeMeasurements = [];
  }

  outputEl.innerText = fps;

  requestAnimationFrame(() => {
    tick();
  });
}

tick();

JSFiddle


1
投票

我错过了一个实现,允许自定义样本的大小为平均FPS值。这是我的,它具有以下特点:

  • 准确:performance.now()基于
  • 稳定:返回的FPS值是一个平均值(fps.value | fps.tick())
  • 可配置:FPS样本数组大小可以自定义(fps.samplesSize)
  • 高效:用于收集样品的旋转阵列(避免阵列调整大小)

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<this._sample_.length; i++) average += this._sample_[ i ];

        average = Math.round( average / this._sample_.length);

        // set new FPS
        this.value = average;
        // store current timestamp
        this._lastTick_ = now;
        // increase sample index counter, and reset it
        // to 0 if exceded maximum sampleSize limit
        this._index_++;
        if( this._index_ === this.sampleSize) this._index_ = 0;
        return this.value;
    }
}


// *******************
// test time...
// *******************

function loop(){
    let fpsValue = fps.tick();
    window.fps.innerHTML = fpsValue;
    requestAnimationFrame( loop );
}
// set FPS calulation based in the last 120 loop cicles 
fps.sampleSize = 120;
// start loop
loop()
<div id="fps">--</div>
© www.soinside.com 2019 - 2024. All rights reserved.