HTML5 Canvas element is used to hold the graphics drawn with JavaScript. Canvas tag is only used to hold the element as a placeholder or container. The actual graphics are drawn with JavaScript. In this article we will draw a simple analog clock using JavaScript and place it on a page with Canvas container.
Related: How to create a rotating cube widget with CSS?
Analog Clock with HTML5 Canvas and JavaScript
This is a simple clock widget with hours, minutes and seconds pointers. The time will start as per your computer’s time when the widget is loaded. Here is a demo of how the clock will look like:
There are two parts in the analog clock widget – JavaScript and Canvas container.
JavaScript for Analog Clock
JavaScript is used to create a circle, pointers, clock time and pointer movements as below. Mathematical calculations are used to divide the 360 degree of the circle for the pointers to rotate appropriately.
<script type="text/JavaScript"> x=150; y=150; clock=document.getElementById("canvas"); ctx=clock.getContext("2d"); function loop() { time=new Date(); h=time.getHours(); m=time.getMinutes(); s=time.getSeconds(); ctx.beginPath(); ctx.fillStyle="white"; ctx.arc(x,y,140,0,Math.PI*2,true); ctx.fill(); ctx.strokeStyle="red"; ctx.lineWidth=10; ctx.stroke(); drawNumber(); drawPointer(360*(h/12)+(m/60)*30-90,70,"black",10); drawPointer(360*(m/60)+(s/60)*6-90,100,"black",10); drawPointer(360*(s/60)+x-90,120,"red",2); } function drawNumber() { for(n=0;n<12;n++) { d=-60; num = new Number(n+1); str = num.toString(); dd = Math.PI/180*(d+n*30); tx = Math.cos(dd)*120+140; ty = Math.sin(dd)*120+160; ctx.font = "26px Verdana"; ctx.fillStyle = "brown"; ctx.fillText(str, tx, ty); } } function drawPointer(deg,len,color,w) { rad=(Math.PI/180*deg); x1=x+Math.cos(rad)*len; y1=y+Math.sin(rad)*len; ctx.beginPath(); ctx.strokeStyle=color; ctx.lineWidth=w; ctx.moveTo(x,y); ctx.lineTo(x1,y1); ctx.stroke(); } setInterval(loop,500); </script>
You can use this script on the page with <script>…<script> tags as given in the code. Otherwise create a .js file and add the content without script tags and link the script file on the footer section of the page using the code <script src=”script.js”></script>.
HTML for Analog Clock
Below is the HTML for the analog clock to create canvas container. You can paste this code anywhere on your page.
<center> <canvas id="canvas" width="300" height="300"></canvas> </center>
Customizing the Widget
The analog clock can be customized with the following options:
- Change the hours, minutes and seconds pointers color and length to any required value defined using drawPointer function.
- Change the size and font of the numbers defined with “ctx.font = “26px Verdana”;”.
- Color of the numbers inside the clock is defined as brown using “ctx.fillStyle = “brown”;” which can be changed to any color.
4 Comments
Leave your reply.