Clock with Javascript 3 ways

 About anolog clock, there are may ways do in Javascript. 

The Math thorey is to calculate the degree depending on how many parts you want to divide.

Because the circle is 360 degree. The basic is one minute equal to 60 seconds, one hour equal to 60 minutes. 

First,  we need a clock on page,so there are several ways.

1.canvas

Acording to W3C clock, it's clear that drawing a canvas is a good visial resolution. with getContext('2d'),and draw the clockface,number and time.

The canvas drawing use the line ,stroke and fill a lot. 
such as the drawFace(), the circle with radius Math,because the circle is 2PI*radius,and fill with color inside.

2.svg

there is a way to use svg in Html.



Like the code, the width and height can be set in html with svg.

Demo more details here

3.html

it's straight to set everything in the html.maybe it's not very decent code,but easy to understand for beginner.

DEMO Github

24 hours display clock below

layout every number and hand in html. And try to manipulate in JS.


Second,when we settle down the clock face,it's time to let it moving. 

The clock is moving every second with setInterval(). All three demos are same. 
every 1000 millisecond, call the function.


Third, what the function can do? we have to grab the current time. 
All three all using newDate() to get the time.


At last,how to calculate the time. 
From W3C demo,calculate the position of hands and then draw it.
every second is 6 degree because of circle is 360 and 60 seconds for a minute,60 minutes for an hour. PI is 180 degree.

Second svg demo is more number calculation.
but the meaning is the same ,but did not related PI

Last one is based on ratio 

Overall, the clock is all about justifying the rotation attributes.
keep fresh the DOM every second

More clock and time related articles:

Popular posts from this blog

Fancyapps — easily build overlay windows with carousel

Thoughts about Progressive Web App

Meet Mantine: A TS-Based Open-Source React Components Library