直接将下列代码复制粘贴即可
const showFPS = (function () {
// noinspection JSUnresolvedVariable, SpellCheckingInspection
const requestAnimationFrame =
window.requestAnimationFrame || // Chromium
window.webkitRequestAnimationFrame || // Webkit
window.mozRequestAnimationFrame || // Mozilla Geko
window.oRequestAnimationFrame || // Opera Presto
window.msRequestAnimationFrame || // IE Trident?
function (callback) { // Fallback function
window.setTimeout(callback, 1000 / 60);
};
let dialog;
let container;
let fps = 0;
let lastTime = Date.now();
function setStyle(el, styles) {
for (const key in styles) {
el.style[key] = styles[key];
}
}
function init() {
dialog = document.createElement('dialog');
setStyle(dialog, {
display: 'block',
border: 'none',
backgroundColor: 'rgba(0, 0, 0, 0.6)',
margin: 0,
padding: '4px', position: 'fixed',
top: 0,
right: 'auto,',
bottom: 'auto',
left: 0,
color: '#fff',
fontSize: '12px',
textAlign: 'center',
borderRadius: '0 0 4px 0'
});
container.appendChild(dialog);
}
function calcFPS() {
let offset = Date.now() - lastTime;
fps += 1;
if (offset >= 1000) {
lastTime += offset;
displayFPS(fps);
fps = 0;
}
requestAnimationFrame(calcFPS);
}
function displayFPS(fps) {
const fpsStr = `${fps} FPS`;
if (!dialog) {
init();
}
if (fpsStr !== dialog.textContent) {
dialog.textContent = fpsStr;
}
}
return function (parent) {
container = parent;
calcFPS();
};
}());
showFPS(document.body);