Mar 032010
 

Analogclock

Here’s a quick analog clock using the HTML5 canvas tag. Oh canvas tag, how I love thee. Click “Read more” for the source. The formatting is a little wonky because I adjusted to fit in the blog. Oh and you can find all my March Madness programs at this page.

JPLT.Class.create("JPLT.Clock",JPLT.Object,

function() {
	this.width = 500;
	this.height= 500;
	this.createElement();
	this.appendElement();
	this.paint();
	this.timer = window.setInterval(this.delegate(this.paint),50);
},

{
context: function() {
	return this.element.getContext("2d");
},
	
createElement: function() {
	this.element = document.createElement("canvas");
	this.element.width = this.width;
	this.element.height = this.height;
	this.element.style.border = "1px solid #ccc";
		
	return this.element;
},

appendElement: function() {
	var body = document.documentElement || document.body;
	body.appendChild(this.element);
},

clear: function() {
	var ctx = this.context();
	ctx.clearRect(0,0,this.width,this.height);
},

paintBackground: function() {
	var ctx = this.context();
	// Save our translate/rotate state because we're going to make a mess of it.
	ctx.save();
	// Set the origin to be the center of the canvas
	ctx.translate(this.width/2, this.height/2);
	ctx.fillStyle = "black";

	for (var i=0; i<12; i++) {
 		// We're just going to keep drawing the 3 o'clock line (horizontal) and rotating
 		ctx.beginPath();
 		ctx.moveTo(this.width/2-35, -5);
 		ctx.lineTo(this.width/2-5, -5);
 		ctx.lineTo(this.width/2-5, 5);
 		ctx.lineTo(this.width/2-35, 5);
 		ctx.lineTo(this.width/2-35, -5);
 		ctx.fill();
 
 		ctx.rotate(Math.PI/6);
 	}
 
 	// Set everything back to normal
 	ctx.restore();
 },
 
 // Paints a hand of the clock.
 // Ratio is the amount around the clock.
 // Size is the size of the hand.
 paintHand: function(ratio, size) {
 	var ctx = this.context();
 
 	// Same approach as before.  Save, rotate, draw horizontally.
 
 	ctx.save();
 
 	ctx.translate(this.width/2, this.height/2);
 	ctx.fillStyle = "black";
 			
 	// Rotate adjusting for 0 radians being 3 o'clock.
 	ctx.rotate(ratio * (2*Math.PI) - (Math.PI/2));
 
 	// Since our origin is now the middle we're working from 0,0
 	ctx.beginPath();
 	ctx.moveTo(0, -size/2);
 	ctx.lineTo(this.width/2-size*3, 0);
 	ctx.lineTo(0, size/2);
 	ctx.lineTo(size, 0);
 	ctx.lineTo(0, -size/2);
 	ctx.fill();
 		
 	ctx.restore();
 },
 
 paint: function() {
 	var d = new Date();
 	var h = d.getHours();
 	var m = d.getMinutes();
 	var s = d.getSeconds();
 	var ms = d.getMilliseconds();
 
 	if (h>12) {
		h -= 12;
	}	

	this.clear();
	this.paintBackground();
	this.paintHand((h*3600+m*60+s)/43200,20);
	this.paintHand((m*60+s)/3600,10);
	this.paintHand((s*1000+ms)/60000,5);
}
}
);