• 一段简单的显示当前页面FPS的代码


    写前端代码,尤其是做一个前端框架的时候,经常需要及时知道代码的大致性能,这时候如果能有个好的办法能一直看到当前页面的fps就好了。

    整体思路是一秒有一千毫秒,先记录当前时间作为最后一次记录fps的时间,通过 requestAnimationFrame 回调不断给累加fsp计数器,并且判断上次记录fps的时间是否达到1000毫秒以上,如果满足条件,就将fps累加器的值作为当前fps显示,并且重置fps累加器。

    这里写了段比较简单的显示FPS的代码:

     1 var showFPS = (function () {
     2     // noinspection JSUnresolvedVariable, SpellCheckingInspection
     3     var requestAnimationFrame =
     4         window.requestAnimationFrame || //Chromium  
     5         window.webkitRequestAnimationFrame || //Webkit 
     6         window.mozRequestAnimationFrame || //Mozilla Geko 
     7         window.oRequestAnimationFrame || //Opera Presto 
     8         window.msRequestAnimationFrame || //IE Trident? 
     9         function (callback) { //Fallback function 
    10             window.setTimeout(callback, 1000 / 60);
    11         };
    12 
    13     var dialog;
    14     var container;
    15 
    16     var fps = 0;
    17     var lastTime = Date.now();
    18 
    19     function setStyle(el, styles) {
    20         for (var key in styles) {
    21             el.style[key] = styles[key];
    22         }
    23     }
    24 
    25     function init() {
    26         dialog = document.createElement('dialog');
    27         setStyle(dialog, {
    28             display: 'block',
    29             border: 'none',
    30             backgroundColor: 'rgba(0, 0, 0, 0.6)',
    31             margin: 0,
    32             padding: '4px',
    33             position: 'fixed',
    34             top: 0,
    35             right: 'auto,',
    36             bottom: 'auto',
    37             left: 0,
    38             color: '#fff',
    39             fontSize: '12px',
    40             textAlign: 'center',
    41             borderRadius: '0 0 4px 0'
    42         });
    43         container.appendChild(dialog);
    44     }
    45 
    46     function calcFPS() {
    47         offset = Date.now() - lastTime;
    48         fps += 1;
    49 
    50         if (offset >= 1000) {
    51             lastTime += offset;
    52             displayFPS(fps);
    53             fps = 0;
    54         }
    55 
    56         requestAnimationFrame(calcFPS);
    57     };
    58 
    59     function displayFPS(fps) {
    60         var fpsStr = fps + ' FPS';
    61 
    62         if (!dialog) {
    63             init();
    64         }
    65 
    66         if (fpsStr !== dialog.textContent) {
    67             dialog.textContent = fpsStr;
    68         }
    69     }
    70 
    71     return function (parent) {
    72         container = parent;
    73         calcFPS();
    74     };
    75 })();
    76 
    77 showFPS(document.body);
  • 相关阅读:
    网络和笔记本
    病毒惹的祸
    Virtual MachineVmware(2)
    VS2010 工具箱装载出错
    Virtual Machine VmWare(1)
    javascript写计数器
    代码自动生成操作
    用live writer写博客
    上海招聘.net程序员
    将用户导入到membership
  • 原文地址:https://www.cnblogs.com/javennie/p/10188253.html
Copyright © 2020-2023  润新知