這是魯棒的方法,使用該方法requestAnimationFrame。
function calcFPS(opts){
var requestFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame;
if (!requestFrame) return true; // Check if "true" is returned;
// pick default FPS, show error, etc...
function checker(){
if (index--) requestFrame(checker);
else {
// var result = 3*Math.round(count*1000/3/(performance.now()-start));
var result = count*1000/(performance.now()- start);
if (typeof opts.callback === "function") opts.callback(result);
console.log("Calculated: "+result+" frames per second");
}
}
if (!opts) opts = {};
var count = opts.count||60, index = count, start = performance.now();
checker();
}
的count
值時,FPS的更精確的值,和較長的FPS測試將越高。
其他邏輯可以用來舍入到15/12s,即24,30,48,60,120 ... FPS。
這裏的編譯版本(舍入到3 FPS):
function calcFPS(a){function b(){if(f--)c(b);else{var e=3*Math.round(1E3*d/3/(performance.now()-g));"function"===typeof a.callback&&a.callback(e);console.log("Calculated: "+e+" frames per second")}}var c=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame;if(!c)return!0;a||(a={});var d=a.count||60,f=d,g=performance.now();b()}
使用像這樣:
calcFPS(); // Only logs to console (you can remove the console log,
// making this call redundant)
calcFPS({count: 30}); // Manually set count (the test should take 500ms
// on a 60FPS monitor
calcFPS({callback: useFPS}); // Specify a callback so you can use the
// FPS number value
var FPS = 0, err = calcFPS({count: 120, callback: fps => FPS = fps});
if (err) FPS = 30;
的問題不是 「如何」,而是 「爲什麼」 。特別是對於後者。 – ThiefMaster 2011-05-25 21:19:25
也許通過使用Native Client和JavaScript? – Shaz 2011-05-25 21:23:34
我無法想象你想在幀刷新時執行回調的情況......你想每秒調用60次什麼函數?你要調用SOMETHING畢竟(假設你可以得到的是首先該信息計數到X幀。 – colinross 2011-05-25 21:23:38