How to create an analog clock using JavaScript and HTML5 canvas

The HTML5 canvas tag is a powerful and flexible feature, here we create an analog clock using JavaScript and HTML5 canvas. It provides an easy way to draw graphics, animations, and other visual effects on web pages without having to use Flash or Java applets. The following tutorial will show you how to create an analog clock using only JavaScript and the HTML5 canvas tag.

What is the HTML5 canvas tag?

The HTML canvas is a new standard in web development. It offers an easy-to-use, powerful way to draw graphics and animations without relying on third-party plugins or Flash.

The HTML canvas is an element in the major browser that you can use to draw graphics, typically using JavaScript. The contents of a canvas are drawn directly on the screen (just like ordinary images), so your page doesn’t need any extra frames or layers for this effect.

You can use the HTML canvas to draw shapes, patterns, or text. You can even animate them!

How to create an analog clock using JavaScript and HTML5 canvas?

In this post, we will show how to create an analog clock using JavaScript and HTML5 canvas tag. All you need is just five simple lines of JavaScript code:

Examples of other clocks created with the HTML5 canvas tag

This is an example of an analog clock using JavaScript and HTML5 canvas.

All you need to do to create your own analog clock using JavaScript and HTML5 canvas elements is a drop in some JavaScript and CSS, as shown below. You can also use images that look like hands on an analog watch face instead of drawing them by hand; it might make your life easier!

Here’s how our code looks …

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{margin: 0;padding: 0; box-sizing: border-box;}
    </style>
</head>
<body>
    <canvas></canvas>

    <script>
        let canvas = document.querySelector('canvas')
        let context = canvas.getContext('2d')
        var linearGradient = context.createLinearGradient(0,0,100,0);
            linearGradient.addColorStop(0  , '#3494E6');
            linearGradient.addColorStop(1, '#EC6EAD');
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        let canvasLength = 600
        let radius = canvasLength / 2;
        context.font = '60px Times'
        context.textAlign = 'center'
        context.textBaseline = 'middle'
        
        
        function analogClock(){
            context.clearRect(0,0,canvas.width,canvas.height);
            
            context.beginPath();
            context.arc(radius,radius ,radius, 0 , Math.PI * 2)
            context.fillStyle = linearGradient;
            context.stroke();
            context.fill()
            context.closePath();
            
            context.beginPath();
            context.translate(radius,radius)
            for(i = 1; i <= 12 ; i++ ){
                let x = radius * 0.9 * Math.cos(((i * 30 - 90) * Math.PI) / 180);
                let y = radius * 0.9 * Math.sin(((i * 30 - 90) * Math.PI) / 180);
                context.fillStyle = '#ffffff'
                context.fillText(i, x,y)

                    context.fill();
                    
                }
                let currentTime = new Date();
                let seconds = currentTime.getSeconds();
                let minutes = currentTime.getMinutes();
                let hours = currentTime.getHours();
                
                let secondAngle = (seconds - 15) * 6
                let minutesAngle = (minutes - 15) * 6
                let hoursAngle = (hours - 3 + minutes / 60) * 30;
                
                context.beginPath();
                drawClockHand(context, secondAngle, radius * 0.75);
                drawClockHand(context, minutesAngle, radius * 0.85);
                drawClockHand(context, hoursAngle, radius * 0.6);
                context.stroke();
                context.closePath();
                
                context.beginPath();
                context.arc(0,0,10, 0 , Math.PI * 2)
                context.fillStyle = '#000'
                context.stroke()
                context.fill()
                context.translate(-radius,-radius)
                

            }

            function drawClockHand(ctx, angle, length){
                context.moveTo(0,0)
                a = length * Math.cos(angle * Math.PI / 180)
                b = length * Math.sin(angle * Math.PI / 180)
                context.lineTo(a, b);
                
            }

            window.onload = setInterval(analogClock,1000);
            
    </script>
</body>
</html>

creating an analog clock using JavaScript and HTML5 canvas
Analog clock using JavaScript and html 5 canvas tag

It is worth noting that raster graphic animations can be created relatively quickly (in comparison to vector-based animation), but it takes many more artists hours or days to create them because they require painting each frame individually rather than using math.

Raster graphics also have another downside – if you lose a single pixel from your original image file then all frames in your animated sequence will show some level of degradation due to data loss – so any reduction in quality has wide-ranging implications for the entire animation!

Vector graphics suffer similarly when their resolution is not high enough.

A vector graphic is an image made up of mathematical commands that define the lines, curves and shapes in a drawing rather than pixels or dots on a grid. Vector graphics can be scaled to any size without losing resolution because they are based on proportions – for example if you add more points to a curve then it will only become fatter not thinner (repetition). This makes them perfect for animation as there’s no data loss when making large changes!

Vector animations have another advantage too: we don’t need individual images per frame so saving time by producing fewer frames means animating with vectors becomes faster too!

The downside? It takes many more hours/days for artists to create vector-based animation due to the amount of time it takes to draw the individual components.

Tips for creating a better-looking clock using the canvas tag

  • The background color is set to a light grey
  • The clock’s hour and minute hands are red, the second hand is green.
  • Font size on all three lines should be at least 16px (or about an inch) tall when viewed in fullscreen.
  • The clock’s second hand is transparent to represent the time moving forward.
  • The hour and minute hands are also animated with a rotation of 0deg, which means they don’t move at all.
  • Animation for the second’s hand should be set to 60px per second (or about one pixel every five milliseconds). This represents each second as six pixels across or 360 degrees in total.
  • The canvas tag that is drawn in the browser should be set to 100% of the screen’s width and height.

Conclusion

The HTML5 canvas tag is a great way to add some visual interest to your website or blog. It’s also an easy and fun project for kids! We hope you enjoyed this tutorial on how to create an analog clock using the HTML5 canvas tag. Let us know what other tutorials you’d like to see in the future, by commenting! and don’t forget to read our other articles. Click here for more articles

Leave a Comment