Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created October 25, 2012 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tmcw/3955066 to your computer and use it in GitHub Desktop.
Save tmcw/3955066 to your computer and use it in GitHub Desktop.
Sleep Chart
var Canvas = require('canvas'),
fs = require('fs');
var keystrokes = fs.readFileSync('../keystrokes_all.log', 'utf8');
var lines = keystrokes.split('\n').slice(1);
var width = 1024, height = 768;
var c = new Canvas(width, height);
var ctx = c.getContext('2d');
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, width, height);
var gaps = {};
for (var i = 0; i < lines.length - 2; i++) {
var gap = +lines[i + 1].split(',')[0] - (+lines[i].split(',')[0]);
var d = new Date(lines[i + 1].split(',')[0] * 1000);
var dayhash = d.getMonth() + '-' + d.getDate();
gaps[dayhash] = (!gaps[dayhash] || gap > gaps[dayhash]) ? gap : gaps[dayhash];
}
var agaps = [];
for (i in gaps) {
agaps.push(gaps[i]);
}
// I don't sleep for more than a day
agaps = agaps.filter(function(g) {
return g < (60 * 60 * 24);
});
ctx.font = '22px Helvetica';
// ctx.textAlign = "center";
var title = 'HOURS OF SLEEP PER NIGHT';
var xm = 0;
var w = ~~(width / agaps.length) + 0;
for (var i = 0; i < agaps.length; i++) {
var hrs = agaps[i] / 6000;
ctx.fillStyle = '#E9E5E0';
ctx.fillRect(xm + 1, 0, w, height);
ctx.fillStyle = '#000';
ctx.fillRect(xm + 1, 0, w, ~~(height * (hrs / 24)));
xm += w + 1;
}
var eight = ~~(height * (8 / 24));
ctx.fillStyle = '#E9E5E0';
ctx.fillRect(160, eight, 155, 40);
ctx.globaAlpha = 1;
ctx.fillStyle = '#222';
ctx.fillRect(0, eight, width, 1);
ctx.fillText('eight hours', 160, eight + 30);
fs.writeFileSync('sleep_new.png', c.toBuffer());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment