Creating a Beautiful Clock Using HTML5 Canvas

Revisiting the clock that I created 4 years back

Subscribe to my newsletter and never miss my upcoming articles

HTML5 provides us with the Canvas API which can be used to draw graphics on a browser using Javascript. We can start drawing graphics in the browser by just adding a canvas tag in HTML. It is similar to the real canvas that we use to paint. We can draw various shapes and texts and animate them using Javascript.

In this article, we will be using HTML5 Canvas and Javascript to create a beautiful clock.

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.

Add Javascript — Logic

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

PART I

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.

PART II

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.

PART III

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

Preview - https://codepen.io/ganeshkumarm/full/MobJdo
Source Code - https://github.com/ganeshkumarm1/CanvasClock

Thank you 🤘

To know more about me, visit ganeshkumarm.me

No Comments Yet