Create an Analog Clock using Javascript

⧉ Category: Programing | 📅 Date: 17 Mar 2024 | अ🉀 Translation:
Create an Analog Clock using Javascript In this post, I am using HTML canvas element to create an image of clock and then use javascript to animate it as ticking clock. What is canvas? HTML5 introduces canvas element which is to create 2d images within the html pages by using javascript. Here is an example: In this example we create a live ticking analog clock, I will explain the procedure step by step. First of all, we need to create a canvas element and set width and height for it. Make sure to add id attribute so that we can call it later by javascript. for now add a color to the background, it will help you spot the canvas easily.
<canvas id="canvas" width="400" height="400" style="background-color: #333333"></canvas>
Let's call the canvas element and store it in variable "canvas", getContext() function is to open the canvas editable and tell javascript that it is a 2D image. Since we are making a clock, name it 'clock' as well. Create a variable and name it 'radius' since we are creating a circle shape clock and radius of the circle is required. And therRadius is half the size of the circle. translate(): here is our first function inside the canvas. Remember the Pencil Compass we used to draw circle when we were in school? translate() function acts like the compass point. it is to mark the starting point of our drawing in the canvas. In other words, we are using translate() to change the current Origin point of the canvas. we need to mark X and Y axis in the canvas using translate(x,y). Currently we use radius as both X and Y axis since it is the center of the canvas.
<script> var canvas = document.getElementById("canvas"); var clock = canvas.getContext("2d"); var radius = canvas.width/2; clock.translate(radius, radius); </script>
Create an Analog Clock using Javascript After setting the Origin point, let's draw a circle to create a Clock-face. We need arc() function to draw a circle in the canvas. before starting, use beginPath() function to break any previous drawing lines and start a new line from here. arc(x, y, radius, starting point, ending point): Since we just set our Origin point, current X and Y are at Zero. we are reducing the radius a little bit(radius*0.9) so that the circle doesn't need to touch the edges of the canvas. About Math.PI measurement, PI is the size of half a circle, so we need 2X PI for full circle (2*Math.PI). the circle needs to be filled with color, we choosing "White" color (fillStyle = "white"). Now we are fill() function just to complete the circle filled with white color.
function clockface(clock, radius) { clock.beginPath(); clock.arc(0, 0, radius*0.9, 0, 2*Math.PI); clock.fillStyle = "white"; clock.fill(); }
Create an Analog Clock using Javascript Adding Numbers: this part is a bit confusing for me as well! I have already mentioned about the PI measurement that it is half a circle. We are splitting 2X PI to 12 pieces because a clock has 12 numbers. 2X PI/12 is equal to PI/6, so what we are doing is, finding the positions of 1-12 numbers in the clock. We are using 'textAlign' and 'textBaseline' to make the numbers perfectly align to the center which is to make sure positioning is correct. Then use 'fillStyle' to color it, and 'font' to assign a font and font size. we are depending on the size of 'radius' a lot since it is the base size of the clock. Now we can make 12 numbers using fillText() function. all the numbers and their positions are different. so we will make a 'for' loop and change the number and its position on each loop. As i said earlier, we are splitting the circle to 12 pieces, so angle size of one piece is (Math.PI/6), we can use multiplication to find the angle size of each numbers in the clock. eg: if n=5, angle size of Number 5 is 5*(Math.PI/6). the 'for' loop will do the work for us. Now we are changing the Origin point again using translate() function to position numbers inside the clock. X will be Zero for all numbers, but Y needs to change to (-radius*0.75). Have you noticed the (-) negative value for Y? it needs to be like that otherwise the clock will be upside down! You will understand when you start the coding by yourself. The code inside the 'for' loop is a bit confusing, - 'rotate' then 'translate', 'rotate' again then fillText() function, again 'rotate', 'translate' and 'rotate'. What actually happening here is simple, once you change the angle and origin point(position) of the canvas for a number, both angle and position need to revert back before we call the next number to move its position and angle. this process keeps doing until all numbers get to their assigned positions. If you still don't have a clue what is happening in this section, just copy and paste whole code to a page, and mess with its values, and try run it, it will give you a hint.
function clocknumber(clock, radius) { clock.textAlign = "center"; clock.textBaseline = "middle"; clock.fillStyle = "#333333"; clock.font = radius*0.2+"px arial"; for(n=1; n<13; n++) { var ang = n*Math.PI/6; clock.rotate(ang); clock.translate(0, -radius*0.75); clock.rotate(-ang); clock.fillText(n.toString(), 0, 0); clock.rotate(ang); clock.translate(0, radius*0.75); clock.rotate(-ang); } }
Create an Analog Clock using Javascript Now the difficult part is over, lets move on to the next part. In this part we are making two functions, one to handle the Time and the other is to control the clock hands. Let me explain the clockhand() function first, clockhand(clock, width, height, pos): (clock-image, width of the hand, height of the hand, position of the hand). As we did earlier, we are starting with beginPath() function since we are drawing clock hands. here we are using stroke() function to draw clock-hands. So, we need to change stroke line width with 'lineWidth' parameter and make the corners of the stroke line rounded with 'lineCap' parameter. To mark the start of stroke line use moveTo() function, to mark the end of stroke line use lineTo() function. MoveTo() is the starting position and LineTo() is the ending position. Then color it using 'strokeStyle' parameter and output the result using stroke() function. As we did earlier, we used rotate() to position the clock-hand angle, then revert the angle back in order to use it by the other clock-hands. Now we can use this function inside the other function clocktime() and control the clock-hands. In the clocktime() function, we have 3 variables called 'hour', 'minute' and 'second' to store the time and convert it to position data. Unlike analog clocks digital time uses whole 24 hour cycle, so we need to change 'hour' variable from full cycle(24h) to half cycle(12h). minutes and seconds are the same (60). For calculating their positions, a circle/12 is an hour, a circle/60 is a minute as well as a second. so the formula is like written below. unlike 'minute' and 'second' hands 'hour' hand positioning can be improved by adding this extra data '((1/60)*minute))' which is the percentage of an hour calculated with the 'minute' data. if we don't include this data, the 'hour' hand will remain in the same position until the next hour completes. You will have to try by yourself with and without including this extra data when you are coding. width and height of the clock-hands can be adjusted as per your preference.
function clocktime(clock, radius) { var date = new Date(); var hour = date.getHours(); if(hour>12) { hour = hour-12; } var minute = date.getMinutes(); var second = date.getSeconds(); var second_pos = ((12*(Math.PI/6))/60)*second; var minute_pos = ((12*(Math.PI/6))/60)*minute; var hour_pos = (Math.PI/6)*(hour+((1/60)*minute)); clockhand(clock, radius*0.05, radius*0.8, minute_pos); clockhand(clock, radius*0.09, radius*0.55, hour_pos); clockhand(clock, radius*0.02, radius*0.8, second_pos); } function clockhand(clock, width, height, pos) { clock.beginPath(); clock.lineWidth = width; clock.lineCap = "round"; clock.rotate(pos); clock.moveTo(0,0); clock.lineTo(0, -height); clock.strokeStyle = "#333333"; clock.stroke(); clock.rotate(-pos); }
And the final part is to create another function and add all other functions we made to this function. Now to make this clock ticking, we can use a setInterval() function and set a (1000ms = 1 second) time interval.
setInterval(createclock, 1000); function createclock() { clockface(clock, radius); clocknumber(clock, radius); clocktime(clock, radius); }
Create an Analog Clock using Javascript Now we have completed the clock. before ending this post, I will add few more lines to this code. 'shadowBlur' and 'shadowColor' to add a faint shadow to the clock-hands. a possible fix to clear the pixelation of clock-face circle which occurs after multiple setInterval() time periods. a custom text inside the clock-face just to make it look a bit realistic. Link to working model: https://postmycode.com/models/analog-clock here is the full code
<canvas id="canvas" width="400" height="400" style="background-color: #333333"></canvas> <script> var canvas = document.getElementById("canvas"); var clock = canvas.getContext("2d"); var radius = canvas.width/2; clock.translate(radius, radius); setInterval(createclock, 1000); function createclock() { clockface(clock, radius); clocknumber(clock, radius); clocktime(clock, radius); clock.beginPath(); clock.shadowBlur = 2; clock.shadowColor = "white"; clock.fillStyle = "#333333"; clock.arc(0, 0, radius*0.08, 0, 2*Math.PI); clock.fill(); clock.shadowBlur = 0; } function clockface(clock, radius) { clock.translate(-radius, -radius); clock.fillStyle = "#333333"; clock.fillRect(0,0, radius*2, radius*2); clock.translate(radius, radius); clock.beginPath(); clock.arc(0, 0, radius*0.9, 0, 2*Math.PI); clock.fillStyle = "white"; clock.fill(); clock.textAlign = "center"; clock.textBaseline = "middle"; clock.font = radius*0.15+"px arial"; clock.fillStyle = "#333333"; clock.fillText("DIZORDAT", 0, -radius*0.35); } function clocknumber(clock, radius) { clock.textAlign = "center"; clock.textBaseline = "middle"; clock.fillStyle = "#333333"; clock.font = radius*0.2+"px arial"; for(n=1; n<13; n++) { var ang = n*Math.PI/6; clock.rotate(ang); clock.translate(0, -radius*0.75); clock.rotate(-ang); clock.fillText(n.toString(), 0, 0); clock.rotate(ang); clock.translate(0, radius*0.75); clock.rotate(-ang); } } function clocktime(clock, radius) { var date = new Date(); var hour = date.getHours(); if(hour>12) { hour = hour-12; } var minute = date.getMinutes(); var second = date.getSeconds(); var second_pos = ((12*(Math.PI/6))/60)*second; var minute_pos = ((12*(Math.PI/6))/60)*minute; var hour_pos = (Math.PI/6)*(hour+((1/60)*minute)); clockhand(clock, radius*0.05, radius*0.8, minute_pos); clockhand(clock, radius*0.09, radius*0.55, hour_pos); clockhand(clock, radius*0.02, radius*0.8, second_pos); } function clockhand(clock, width, height, pos) { clock.beginPath(); clock.lineWidth = width; clock.lineCap = "round"; clock.shadowBlur = 2; clock.shadowColor = "white"; clock.rotate(pos); clock.moveTo(0,0); clock.lineTo(0, -height); clock.strokeStyle = "#333333"; clock.stroke(); clock.rotate(-pos); } </script>
«[Previous Post] How to change server timezone to local timezone in..How to Connect Your Smartphone or Laptop to a WiFi.. [Next Post]»

Comments

Please solve above captcha based on the hint given..
f