寫前端程式碼,尤其是做一個前端框架的時候,經常需要及時知道程式碼的大致效能,這時候如果能有個好的辦法能一直看到當前頁面的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);