@kchrv/fpsmeter
Version:
Count frames per second
103 lines (81 loc) • 2.11 kB
JavaScript
class FPSMeter {
constructor () {
Object.defineProperty(this, 'fps', {
get () {
return this.currentFps()
}
})
Object.defineProperty(this, 'lostFrames', {
get () {
let lostFrames = 0
if (this.time > 17) {
lostFrames = parseFloat((this.time / 16.66).toFixed(2))
}
return lostFrames
}
})
this.deltaTimes = []
this.t1 = performance.now()
this.active = false
this.initFpsText()
this.start()
}
initFpsText () {
this.fpsText = document.createElement('div')
this.fpsText.style.position = 'fixed'
this.fpsText.style.top = '1%'
this.fpsText.style.left = '1%'
this.fpsText.style.color = 'yellow'
this.fpsText.style.fontSize = '1vw'
this.fpsText.style.fontFamily = 'sans-serif'
this.fpsText.style.zIndex = 999
this.fpsText.style.display = 'none'
document.body.appendChild(this.fpsText)
}
currentFps () {
if (!this.deltaTimes.length) return 0
return parseInt(1 / ((this.deltaTimes.reduce((a, b) => a + b) / this.deltaTimes.length) / 1000))
}
getFps (frames) {
if (frames) {
return (frames * this.currentFps()) / 60
} else return this.currentFps()
}
newTimestamp () {
this.time = performance.now() - this.t1
this.t1 = performance.now()
return this.time
}
addTimeStamp () {
this.deltaTimes.push(this.time)
if (this.deltaTimes.length > 300) {
this.deltaTimes.shift()
}
return this
}
update () {
if (!this.active) return
this.newTimestamp()
this.addTimeStamp()
this.updateFps()
requestAnimationFrame(this.update.bind(this))
}
updateFps () {
this.fpsText.innerHTML = this.fps + 'fps'
}
start () {
this.active = true
this.update()
return this
}
stop () {
this.active = false
}
showFps () {
this.fpsText.style.display = ''
}
hideFps () {
this.fpsText.style.display = 'none'
}
}
exports.FPSMeter = FPSMeter