Abstract: Today I will teach you to write a canvas clock case, the effect may seem relatively simple, without those fancy.

This article is shared from Huawei cloud community “How to achieve a plain Canvas clock effect” by: Northern Lights night.

First look at the effect

Write a canvas clock example today. The effect may look simple and not flashy, but it involves a lot of canvas knowledge, which is a must for beginners to learn canvas. Here’s a quick way to do it

2. Implementation steps (source code 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;
      }
Copy the code

2. Start js code implementation, the following for easy to understand, so a function encapsulates a function:

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

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

In order to rotate to the center of the. Clock later, offset translate 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(); }Copy the code

4. Draw the 12-digit clock:

We know that the x coordinate of a circle is R times cosine (its Angle), and the y coordinate is R times sine (its Angle). Also, because math.cos () and Math.sin () calculate radians, they convert. Formula: Radians = Angle * π / 180

Function hourNum() {var arr = [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12]; ctx.beginPath(); // The basic style of the number 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) ); }}Copy the code

5. Draw the clock center dot:

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();
      }
Copy the code

6. Draw an hour hand:

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

Function hourHand(hours, minutes) {function hourHand(hours, minutes) {// The rotation Angle, the default clock is 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(); CTX. LineWidth = 5; Ctx. lineCap = "round"; ctx.strokeStyle = "black"; / / rotating CTX. Rotate (radius); // Draw a line to represent the clock ctx.moveto (0, 0); ctx.lineTo(0, -50); ctx.stroke(); // Return to the saved state ctx.restore(); }Copy the code

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();
      }
Copy the code

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();
      }
Copy the code

9. Wrap a function to get the current time:

At the same time, all drawn functions are called internally. Implementation draws 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 ctx.save() when drawing the chassis; drawPanel(); hourNum(); secondHand(seconds); minuteHand(minutes); hourHand(hours, minutes); centerDot(); // Restore the canvas state ctx.restore(); } update();Copy the code

10. Start the timer, clock operation:

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

3. To summarize

The above content is all. It is not difficult to implement. It is a good practice to use some methods provided by Canvas reasonably. Source code in my Gitee repository directly to download or copy gitee.com/aurora-in-w…

Click to follow, the first time to learn about Huawei cloud fresh technology ~