Timelines - Canvas (Separate Redraws)
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.init();
};
Timeline.prototype = Timeline;
Timeline.init = function() {
this.resize();
};
Timeline.resize = function() {
this.canvas[0].height = this.container.innerHeight();
this.canvas[0].width = this.container.innerWidth() - 3;
};
Timeline.draw = function(refresh) {
var canvas = this.canvas[0],
ctx = canvas.getContext("2d"),
offset = 0;
if (refresh == undefined) refresh = 20;
ctx.strokeStyle = "white";
tickMarks(ctx, 0, canvas.height, 20, 20, offset);
setInterval(function() {
var inc = 20;
offset++;
if (offset >= inc) {
offset = 0;
}
Canvas.clear(canvas);
tickMarks(ctx, 0, canvas.height, 20, 20, offset);
// Vertical line
ctx.beginPath();
ctx.moveTo(20, 0);
ctx.lineTo(20, canvas.height);
ctx.stroke();
}, refresh);
};
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) {
...