Clock Demo Fork

by Jason_Knight

HTML

<canvas id="canvas" width="400" height="400"
style="background-color:#333">
</canvas>

JavaScript

(function(d) {

	var
		canvas = document.getElementById("canvas"),
		ctx = canvas.getContext("2d"),
		radius = canvas.height / 2;

	ctx.translate(radius, radius);
	radius *= 0.90
	drawClock();
	setInterval(drawClock, 1000);

	function drawClock() {
		drawFace();
		drawNumbers();
		drawTime();
	}

	function drawFace() {
		var grad = ctx.createRadialGradient(0,0,radius*0.95, 0,0,radius*1.05);
		grad.addColorStop(0, '#333');
		grad.addColorStop(0.5, 'white');
		grad.addColorStop(1, '#333');
		ctx.beginPath();
		ctx.arc(0, 0, radius, 0, 2 * Math.PI);
		ctx.fillStyle = 'white';
		ctx.fill();
		ctx.strokeStyle = grad;
		ctx.lineWidth = radius * 0.1;
		ctx.stroke();
		ctx.beginPath();
		ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
		ctx.fillStyle = '#333';
		ctx.fill();
	}

	function drawNumbers() {
		ctx.font = radius * 0.15 + "px arial";
		ctx.textBaseline = "middle";
		ctx.textAlign ="center";
		var
			pos = radius * 0.85,
			inc = Math.PI / 6,
			ang = inc * 7;
		for (var num = 1; num < 13; num++) {
			ctx.save();
			ctx.rotate(ang);
			ctx.translate(0, pos);
			ctx.rotate(-ang);
			ctx.fillText(num.toString(), 0, 0);
			ctx.restore();
			ang += inc;
		}
	} // drawNumbers

	function drawTime(){
		var
			sxd2Rad = Math.PI / 30,
			now = new Date();
		drawHand(
			(now.getHours() * 5 + Math.floor(now.getMinutes() / 12)) * sxd2Rad,
			0.5,
			0.07
		);
		drawHand(
			now.getMinutes() * sxd2Rad,
			0.75,
			0.07
		);
		drawHand(
			now.getSeconds() * sxd2Rad,
			0.85,
			0.02
		);
	} // drawTime

	function drawHand(pos, length, width) {
		ctx.save();
		ctx.beginPath();
		ctx.lineWidth = width * radius;
		ctx.lineCap = "round";
		ctx.rotate(pos);
		ctx.moveTo(0, 0.25 * radius);
		ctx.lineTo(0, -length * radius);
		ctx.stroke();
		ctx.restore();
	} // drawHand

})(document);