Creating a Beautiful Clock Using HTML5 Canvas
Revisiting the clock that I created 4 years back
Add HTML — Layout
First, we will start by adding an HTML file with a canvas tag
Add CSS — Style
Next, we will add a CSS file that contains some basic styling for the body tag.
The clock contains texts and different shapes like Rectangle, Arc, etc. We will be adding the code to create those basic shapes.
In the above file, we added logic to create Rectangle, Circle, and Text.
Next, we will add the code to render the clock based on the current time. For that, we need to add a few logic to decide the current position of the hour, minute and seconds hand.
Our script contains 3 parts.
PART I - Line 1 to 26
PART II- Line 29 to 40
PART III- Line 45 to 92
Here we query the canvas element and initialize a 2D context as we are going to work on a 2D plane. We also defined few variables which hold the color of hour, minute, and seconds hand.
Here we have an init method that will be called while executing the script. Inside the init method, we defined the width and height of the canvas. Also, we called the method window.requestAnimationFrame with the draw method (line 45) as the parameter. The window.requestAnimationFrame executes the method 60 times per second thus making it an animation.
Here we have added the core logic which calculates the current position of the hour, minute, and seconds hand based on the current time. Since the requesAnimationFrame method is called repeatedly, the canvas is repainted with the new position of the hands based on the time.
Finally, the clock looks awesome.
Preview - https://codepen.io/ganeshkumarm/full/MobJdo
Source Code - https://github.com/ganeshkumarm1/CanvasClock
Thank you 🤘
To know more about me, visit ganeshkumarm.me