Last active
August 29, 2015 14:01
-
-
Save maxwihlborg/b7c60f991d98a03006cd to your computer and use it in GitHub Desktop.
Simple FPS Counter for JavaScript games
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var stats = { | |
fps: 0, | |
frames: 0, | |
_prevtime: 0, | |
_ticktime: 0, | |
_tickint: 100, | |
_tickval: 0, | |
_sum: 0, | |
_idx: 0, | |
_initialized: false, | |
_stack: [], | |
_slen: 0, | |
create: function(fps) { | |
if (typeof window.performance === 'undefined') { | |
window.performance = {}; | |
} | |
if (!window.performance.now){ | |
window.performance.now = function(){ | |
return Date.now(); | |
} | |
} | |
var _f = 1000 / (fps || 60); | |
this._stack = []; | |
for (var i = 10;i--;) { | |
this._stack.push(_f); | |
this._sum += _f; | |
} | |
this._slen = this._stack.length; | |
this._prevtime = window.performance.now() - _f; | |
this._initialized = true; | |
}, | |
update: function() { | |
if (!this._initialized) { | |
this.create(); | |
} | |
this.frames++; | |
var now = window.performance.now(); | |
var ms = now - this._prevtime; | |
this._prevtime = now; | |
this._sum -= this._stack[this._idx]; | |
this._sum += ms; | |
this._stack[this._idx] = ms; | |
this._idx = (this._idx + 1) % this._slen; | |
return this.fps = 1000*this._slen / this._sum; | |
}, | |
draw: function(ctx, x, y, clr) { | |
x = x || 10; | |
y = (y || 10) + 16; | |
clr = clr || "#FF0"; | |
if (this._ticktime < this._prevtime) { | |
this._ticktime = this._prevtime + this._tickint; | |
this._tickval = this.fps.toFixed(1); | |
} | |
ctx.save(); | |
ctx.font = "100 16px Helvetica"; | |
ctx.fillStyle = clr; | |
ctx.fillText(this._tickval, x, y); | |
ctx.restore(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment