So from my last little assignment I’ve written a simple JavaScript digital clock. Now I am going to build an analog clock by reusing my previous code.
To write a JavaScript analog clock, we can use the powerful HTML5 canvas element. The canvas element allows you to use JavaScript (with a 2D drawing API) to draw graphics, you can find an excellent tutorial here.
Most of the modern browsers support the canvas element, except our ‘friend’ IE, which dominates the browsers market. In order to make use of the powerful canvas element in IE, we will need to include some 3rd party script like Explorer Canvas.
Back to my analog clock assignment, basically the internal calculations of a digital clock object and an analog clock object should be the same, the only difference is just the presentation. The quickest way to reuse my code is to let the analog clock object inherits the digital clock object, and then we override the analog clock’s presentation logic.
In JavaScript, we can make new object by extending old object using Prototypal Inheritance. Simply speaking, prototypal inheritance allows new object to be created by copying old object’s properties.
In order to create the analog clock object based on the existing digital clock object we do the following:
www.ui.AnalogClock.prototype = new www.ui.Clock();
The next step is to override the presentation logic. What I need is just simply overriding the redraw method of the clock:
// Override redraw method
www.ui.AnalogClock.prototype.redraw = function() {
var container = this.container;
// Analog clock drawing logic here
};
I am not going into details of the clock drawing logic, I actually learned from this article in developer.apple.com.
You can find the working sample here, and the analog clock script (minified version).
flashplayer
Gut!