写前端代码,尤其是做一个前端框架的时候,经常需要及时知道代码的大致性能,这时候如果能有个好的办法能一直看到当前页面的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.setTimeoutcallback, 1000 / 60); 11 }; 12 13 var dialog; 14 var container; 15 16 var fps = 0; 17 var lastTime = Date.now); 18 19 function setStyleel, 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 setStyledialog, { 28 display: 'block', 29 border: 'none', 30 backgroundColor: 'rgba0, 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.appendChilddialog); 44 } 45 46 function calcFPS) { 47 offset = Date.now) - lastTime; 48 fps += 1; 49 50 if offset >= 1000) { 51 lastTime += offset; 52 displayFPSfps); 53 fps = 0; 54 } 55 56 requestAnimationFramecalcFPS); 57 }; 58 59 function displayFPSfps) { 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 showFPSdocument.body);
