Just in case you misplaced you watch or don’t want to look at the ugly digital display in the corner of your computer, here’s a beautiful, smooth motion, analog clock written in vanilla JavasScript. (I know, it’s basically useless, but it was a fun exercise to brush up on my trigonometry and keep my JS chops up.)
Check out the CodePen to review code:
See the Pen Smooth Motion JS Analog Clock by Doli Stepniewski (@viction) on CodePen.
JavaScript Highlights
This post isn’t a tutorial, per se, but more of a showcase of some of the fun things HTML canvas and JavaScript can do together.
The trickiest part for me was calculating smooth, sweeping hand movements. Since sine and cosine methods are based on radians (instead of degrees), I had to first find the number of steps in a circle’s circumference for hours, minutes, and seconds, then calculate the [x, y] plot points in a 2 dimensional space.
Since there are 2 PI worth of radians in a sine or cosine full cycle, I had to divide 2 PI by hours, minutes, and seconds respectively. However, using actual 12, 60, 60 gives choppy, exact hand movement.
Here’s how I calculated a sweeping motion for the second hand. Lucky for us, the Date
class provides milliseconds for current time, so dividing Math.PI * 2
worth of radians by seconds * 1000 + milliseconds
gives us the proper radians to pass to sine and cosine methods. See example for millisecond (second hand) calculations below.
const amplitude = 100 // size of radius const dateOb = new Date(); const second = dateOb.getSeconds() const ms = dateOb.getMilliseconds() const radians = (second * 1000 + ms )* (Math.PI * 2 / 60 / 1000) const x = Math.sin(radians) * amplitude const y = -Math.cos(radians) * amplitude // plot line [centerx, centery] to [centerx + x, centery + y] on canvas to get the second hand position
Then do the same type of thing with hours and minutes – sweeping hours = hours * 60 + minutes
; sweeping minutes = minutes * 60 + seconds
. Download and review the code at bitbucket.org/viction/doli-clock.
Let me know in the comments if you have any questions or have a better solution to any part of my clock script.
I’ll be using this simple SPA in upcoming posts: Containerize a Single Page App and Deploy Your Apps as Server-less Cloud Services.