Teach you to achieve a simple Canvas clock effect

Keywords: Javascript html5 html canvas

Abstract: today I'll teach you to write a canvas clock case. The effect may look simple without those fancy ones.

This article is shared from Huawei cloud community< How to realize a simple Canvas clock effect >, author: Aurora Borealis night..

1, First look at the effect:

Write a clock case of canvas today. The effect may seem relatively simple without those fancy ones. However, it involves a lot of canvas knowledge points. It is necessary for beginners to learn canvas. Let's take you hand-in-hand to realize it quickly~

2, Implementation steps (the source code is at the end):

1. Set basic labels and styles:

    <div class="clock">
      <canvas width="300" height="300" id="canvas"></canvas>
    </div>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgb(204, 204, 204);
      }
      .clock {
        width: 300px;
        height: 300px;
        background-color: rgb(15, 15, 15);
        border-radius: 50px;
      }

2. Start js code implementation. For ease of understanding, one function encapsulates one function:

  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

3. First draw the overall white chassis of the clock:

At the same time, in order to set the rotation point to the center of. clock later, translate is offset by half.

function drawPanel() {
        ctx.translate(150, 150);
        // Start drawing
        ctx.beginPath();
        // Draw a circle
        ctx.arc(0, 0, 130, 0, 2 * Math.PI);
        ctx.fillStyle = "white";
        ctx.fill();
      }

4. Draw 12 digits of the clock:

It can be seen that the x coordinate of a circle is R * cos (its angle) and the y coordinate is R *sin (its angle).
At the same time, because Math.cos() and Math.sin() calculate radians, they need to be converted. Formula: radian = angle * π / 180

function hourNum() {
        // Store 12 numbers
        var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        ctx.beginPath();
        // Basic style of numbers
        ctx.font = "30px fangsong";
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.fillStyle = "black";
        for (var i = 0; i < arr.length; i++) {
          ctx.fillText(
            arr[i],
            108 * Math.cos(((i * 30 - 60) * Math.PI) / 180),
            108 * Math.sin(((i * 30 - 60) * Math.PI) / 180)
          );
        }
      }

5. Draw the dot in the center of the clock:

A gray circle covers a slightly larger black circle.

function centerDot() {
        ctx.beginPath();
        ctx.arc(0, 0, 8, 0, 2 * Math.PI);
        ctx.fill();
        ctx.beginPath();
        ctx.fillStyle = "gray";
        ctx.arc(0, 0, 5, 0, 2 * Math.PI);
        ctx.fill();
      }

6. Draw the hour hand:

Suppose that the parameters hours and minutes are the hours and minutes of the current time passed in.

function hourHand(hours, minutes) {
        // The angle that should be rotated. The default clock is pointing to 12 o'clock.
        var radius =
          ((2 * Math.PI) / 12) * hours + (((1 / 6) * Math.PI) / 60) * minutes;
       // Save the current state in order to return to the original state after rotation.
        ctx.save();
        ctx.beginPath();
        // Needle width
        ctx.lineWidth = 5;
        // The needle is rounded
        ctx.lineCap = "round";
        ctx.strokeStyle = "black";
        // rotate
        ctx.rotate(radius);
        // Draw a line to represent the clock
        ctx.moveTo(0, 0);
        ctx.lineTo(0, -50);
        ctx.stroke();
        // Return to saved state
        ctx.restore();
      }

7. Similarly, draw the minute hand:

 function minuteHand(minutes) {
        2 * Math.PI;
        var radius = ((2 * Math.PI) / 60) * minutes;
        ctx.save();
        ctx.beginPath();
        ctx.lineWidth = 3;
        ctx.lineCap = "round";
        ctx.strokeStyle = "black";
        ctx.rotate(radius);
        ctx.moveTo(0, 0);
        ctx.lineTo(0, -70);
        ctx.stroke();
        ctx.restore();
      }

8. Similarly, draw the second hand:

function secondHand(seconds) {
        var radius = ((2 * Math.PI) / 60) * seconds;
        ctx.save();
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.lineCap = "round";
        ctx.strokeStyle = "red";
        ctx.rotate(radius);
        ctx.moveTo(0, 0);
        ctx.lineTo(0, -90);
        ctx.stroke();
        ctx.restore();
      }

9. Encapsulate a function to obtain the current time:

At the same time, all drawn functions are called inside the function. Realize drawing a complete clock.

function update() {
        var time = new Date();
        var hours = time.getHours();
        var minutes = time.getMinutes();
        var seconds = time.getSeconds();
        // Save the canvas state because it is offset when drawing the chassis
        ctx.save();
        drawPanel();
        hourNum();
        secondHand(seconds);
        minuteHand(minutes);
        hourHand(hours, minutes);
        centerDot();
         // Restore canvas state
        ctx.restore();
      }
      update();

10. Start the timer and the clock runs:

  setInterval(() => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    update();
  }, 1000);

3, Summary:

The above is the whole content. It's not difficult to implement. It's just to make rational use of some methods provided by canvas. It's very good to practice. The source code is directly downloaded or copied in my gitee warehouse obtain 👉: Blog: blog address auroras.blog.csdn.net (css, js, canvas special effect source code)

Click focus to learn about Huawei cloud's new technologies for the first time~

Posted by Molly on Thu, 18 Nov 2021 20:54:48 -0800