Timelines - Canvas (Event Loop)
by justjohn
HTML
<div id="timelines" class="timelines"></div>
<div class="stats">Time: <span class="time"></span></div>
CSS
body {
background: #555;
}
.timelines {
position: absolute;
left: 20px;
right: 20px;
top: 20px;
bottom: 40px;
border: 2px solid black;
background: #333;
}
.timeline_container {
position: absolute;
overflow: hidden;
height: 100%;
left: 0;
top: 0;
background: #333;
}
.timeline_container .timeline {
border: 0;
border-right: 1px solid #AAA;
border-left: 1px solid #AAA;
}
.stats {
position:absolute;
bottom: 10px;
height: 20px;
left:30px;
}
JavaScript
var Canvas = {
clear: function(canvas) {
var ctx = canvas.getContext("2d");
// Store the current transformation matrix
ctx.save();
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
ctx.restore();
}
};
var Timeline = function(params) {
var parent = $(params.container)
, container = $('<div class="timeline_container"></div>')
, canvas = $('<canvas class="timeline"></canvas>');
container.append(canvas);
parent.append(container);
this.container = container;
this.canvas = canvas;
this.parent = parent;
this.offset = 0;
this.speed = params.speed;
this.resize();
};
Timeline.prototype = Timeline;
Timeline.resize = function() {
this.canvas[0].height = this.container.innerHeight();
this.canvas[0].width = this.container.innerWidth() - 3;
};
Timeline.draw = function() {
var canvas = this.canvas[0],
ctx = canvas.getContext("2d"),
inc = 20;
this.offset++;
if (Math.floor(this.offset / this.speed) >= inc) {
this.offset = 0;
}
Canvas.clear(canvas);
tickMarks(ctx, 0, canvas.height, 20, 20, Math.floor(this.offset / this.speed));
// Vertical line
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.moveTo(20, 0);
ctx.lineTo(20, canvas.height);
ctx.stroke();
};
function tickMarks(ctx, start, end, inc, left, offset) {
var tickMarkConfig = {
color: "white",
width: 10
};
if (offset === undefined) offset = 0;
ctx.strokeStyle = tickMarkConfig.color;
var i;
for (i = start; i < end; i += inc) {
ctx.beginPath();
ctx.moveTo(left, i + offset);
ctx.lineTo(left + tickMarkConfig.width, i + offset);
ctx.stroke();
}
}
var timelines =...