Skip to content

Instantly share code, notes, and snippets.

@wwqrd
Created July 31, 2012 21:17
Show Gist options
  • Save wwqrd/3220649 to your computer and use it in GitHub Desktop.
Save wwqrd/3220649 to your computer and use it in GitHub Desktop.
A simple stats display
(function() {
var Stats = function() {
var d = document.createElement("div");
d.setAttribute("style","color:#fff;font-size:10px;position:absolute;top:2px;left:2px;width:80;height:30px;padding:5px;z-index:1000;background:rgba(0,0,0,0.85);");
document.getElementsByTagName("body")[0].appendChild(d);
this.d = d;
this.stats = {};
this.measurements = {};
};
Stats.prototype.add = function(stat,options) {
var options = options || {};
if(!this.stats[stat]) {
this.stats[stat] = options;
this.measurements[stat] = [];
};
}
Stats.prototype.measurement = function(stat, value) {
if(this.measurements[stat]) {
if(this.measurements[stat].length >= 16) {
this.measurements[stat].shift();
}
this.measurements[stat].push(value);
};
};
Stats.prototype.loop = function() {
this.draw();
}
Stats.prototype.draw = function() {
this.d.innerHTML = "";
for(var i in this.stats) {
switch(this.stats[i].mode) {
case 'bars':
this.d.innerHTML += this.stats[i].label+": "+this.getBars(i);+"<br />";
break;
default:
this.d.innerHTML += this.stats[i].label+": "+this.measurements[i][this.measurements[i].length-1];+"<br />";
}
}
}
Stats.prototype.getBars = function(stat) {
var html = "";
if(this.stats[stat]) {
html = "<div style='position:relative;height:20px;width:80px;'>";
var s = this.stats[stat];
var av = 0;
var min = 1000000;
var max = 0;
for(var i in s) {
av += s[i];
max = (s[i] > max ? s[i] : max);
min = (s[i] < max ? s[i] : max);
}
av /= s.length;
var d = 20; //max-min-1;
for(var i in s) {
var l = i*5;
//var h = (s[i]-min+1)*d;
var h = (s[i]/max)*d;
html += "<div style='position:absolute;background:rgba(255,255,255,0.85);bottom:0;width:5px;left:"+l+"px;height:"+h+"px;'></div>";
}
html += "</div>";
}
return html;
}
Stats.prototype.start = function() {
if(!this.running) {
var self = this;
this.timer = setInterval(function() {
self.loop();
},1000/24);
this.running = true;
}
}
Stats.prototype.stop = function() {
clearInterval(this.timer);
this.running = false;
}
window.addEventListener('load', function() {
window.stats = new Stats();
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment