JavaScript查看FPS

image.png

同发掘金

chrome的Rendering面板中的FPS meter可以实时查看当前页面的FPS(frames per second)和简单的GPU信息
但是:它只在某一帧发生变化时才会计数,如果啥都不干,js主线程是空闲的,帧率会很低-按我的理解也就是不太准,我们可以自己实现查看当前页面帧率的函数。


image.png

JavaScript查看FPS的几种方式, 主要都是利用了requestAnimationFrame,使浏览器在下次重绘之前执行回调

1 使用requestAnimationFrame结合performance

const times = []; // 存储当前的时间数组
let fps;
function refreshLoop() {
  window.requestAnimationFrame(() => {
    const now = performance.now(); // 使用performance.now()能获取更高的精度
    while (times.length > 0 && times[0] <= now - 1000) {
      times.shift(); // 去掉1秒外的时间
    }
    times.push(now);
    fps = times.length;
    refreshLoop();
    console.log(fps);
  });
}

refreshLoop();

2 使用requestAnimationFrame

var before,now,fps;
before=Date.now();
fps=0;
requestAnimationFrame(
    function loop(){
        now=Date.now();
        fps=Math.round(1000/(now-before));
        before=now;
        requestAnimationFrame(loop);
        console.log("fps",fps)
    }
 );

3 使用requestAnimationFrame2 配置进度条

html

<progress id="kpFps" value="0" min="0" max="100" style="vertical-align:middle"></progress>

javascript

let be = Date.now(),fps=0;
requestAnimationFrame(
    function loop(){
        let now = Date.now()
        fps = Math.round(1000 / (now - be))
        be = now
        requestAnimationFrame(loop)
        if (fps < 35){
          kFps.style.color = "red"
          kFps.textContent = fps 
        } if (fps >= 35 && fps <= 41) {
            kFps.style.color = "deepskyblue"
            kFps.textContent = fps + " FPS"
          } else {
            kFps.style.color = "black"
            kFps.textContent = fps + " FPS"
        }
        kpFps.value = fps
    }
 )
image.png

怎么用?

  • 打开你想要测试的web,把上面的代码copy到控制台执行
  • 或者放到你的web中的js中
image.png
image.png

参考

1、check-fps-in-js
2、Fast and Simple JavaScript FPS Counter
3、requestAnimationFrame
4、Performance

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。