JavaScript canvas to achieve colorful clock effect

JavaScript canvas to achieve colorful clock effect

Use canvas to write a colorful clock!

1. Title

(1) You are given a clock case and are asked to draw a clock on the page and obtain the current system time of the computer? (The style is not limited to h5)

2. Ideas

(1) First, we need to fully understand the graphics in the canvas element and how to draw line segments, circles, hour hands, minute hands, and second hands;
(2) Secondly, it is necessary to render a clock graphic in the page layout, draw the position of the scale, and the static effect of the position of the hour hand, minute hand, and second hand, so that the timer can achieve dynamic effects later;
(3) After completing these tasks, the most difficult part is how to make the hour hand, minute hand and second hand correspond to the scale one by one. Then we need to use the arc system of a circle and let the timer call the clock function every second.
(4) To achieve these effects, save and clear the canvas in time to avoid bugs; (5) Use JavaScript to render to the page to achieve the function;

3. Effect display diagram

4. Writing

Get time:

Get the current system time: Use the time object to get the current accurate time. Since the time is not an integer, we have to convert the time into a floating point decimal. In order to facilitate the subsequent timer call, there is currently no 13, 14, 15... So we use a ternary expression to convert the 24-hour system to a 12-hour system.

Since the minute scale is the same as the hour scale, I will briefly explain it using the hour scale as an example:

  • Use the for loop to loop 12 times, because there are 12 hour hand scales, which is convenient for drawing the following scales;
  • Set the center point of the canvas as the origin of the circle and rotate the canvas;
  • A perfect circle is 360 degrees, which is divided into 12 equal parts. Each scale needs to rotate 30 arcs. The canvas rotates 30 arcs each time, and it rotates 12 times.
  • Draw the scale and give it a random color style;

Hour hand drawing (hour hand and minute hand are basically the same):

  • First, you need to save the canvas state and set the line thickness and color;
  • Reset the origin of the canvas to the center of the canvas;
  • The hour hand needs to rotate 30 arcs each time, according to the rotation of the second hand and minute hand;
  • Draw the hour hand segment and render it to the hour hand page;

Draw the center of the dial:

  • Find the center of the canvas circle;
  • Draw a solid origin with a radius of 4 at the center of the circle as the intersection (center point) of the three pointers of hours, minutes and seconds;

Draw text time:

The system time has been obtained above, we just need to set its style and position and render it to the clock page!

5. Reference code block

<!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>
</head>
<body>
    <canvas id="clock" width="500" height="500" ></canvas>
    <script>
        var canvas = document.getElementById("clock");
        var context = canvas.getContext("2d");
        
        // canvas.style.backgroundColor=getRandom()
        function drawClock(){
        // Clear the canvas context.clearRect(0,0,canvas.width,canvas.height)
        //Get the time var now = new Date()
        var second = now.getSeconds()
        var minute = now.getMinutes()
        var hour1 = now.getHours()
        var hour=hour1+minute/60; //Convert 24-hour system to 12-hour system, and use floating point type hour=hour>12?hour-12:hour;
        var time=now.toLocaleString() //Get the total time //Draw the dialcontext.beginPath() //Start pathcontext.strokeStyle=getRandom() //Line colorcontext.lineWidth=8 //Line thicknesscontext.arc(250,250,200,0,360,false)
        context.stroke()
        context.closePath() //End path //Drawing time scale for(var i=0;i<12;i++){
            context.save() //Save the current canvas state context.translate(250,250) //Reset the origin of the canvas to the center of the canvas context.lineWidth=3;    
            context.rotate(Math.PI/180*30*i) //Set the rotation angle of the canvas. The parameter is radians Math.PI/180*30
            context.beginPath()
            context.strokeStyle = getRandom()
            context.moveTo(0,-180) //Starting position context.lineTo(0,-195) //Ending position context.stroke()        
            context.closePath()
            context.restore()

        }
        //Draw the scale for(var i=0;i<60;i++){
            context.save() //Save the current canvas state context.translate(250,250) //Reset the origin of the canvas to the center of the canvas context.lineWidth=1;    
            context.rotate(Math.PI/180*6*i) //Set the canvas rotation angle, the parameter is radians Math.PI/180*30
            context.beginPath()
            context.strokeStyle = getRandom()
            context.moveTo(0,-188) //Starting position context.lineTo(0,-195) //Ending position context.stroke()        
            context.closePath()
            context.restore()

        }
        //Hour hand context.save()
        context.lineWidth=5;
        context.strokeStyle = getRandom()
        context.translate(250,250)
        context.rotate(hour*30*Math.PI/180)
        context.beginPath()
        context.moveTo(0,10)
        context.lineTo(0,-100)
        context.stroke()
        context.closePath()
        context.restore()

        //Minute hand context.save()
        context.lineWidth=3;
        context.strokeStyle = getRandom()
        context.translate(250,250)
        context.rotate(minute*6*Math.PI/180)
        context.beginPath()
        context.moveTo(0,15)
        context.lineTo(0,-130)
        context.stroke()
        context.closePath()
        context.restore()

         //Second hand context.save()
        context.lineWidth=1;
        context.strokeStyle = getRandom()
        context.translate(250,250)
        context.rotate(second*6*Math.PI/180)
        context.beginPath()
        context.moveTo(0,15)
        context.lineTo(0,-170)
        context.stroke()
        context.closePath()
        context.restore()
        
        //Dial center context.beginPath()
        context.lineWidth=1;
        context.fillStyle="red"
        context.arc(250,250,4,0,360,false)
        context.fill()
        context.closePath()

        //Draw text time context.font="18px Songti Bold"
        context.fillStyle = getRandom()
        context.fillText(time,160,150)
        }
        drawClock()
        setInterval(drawClock,1000)

        function getRandom(){
            var col="#";
            for(var i=0;i<6;i++){
              col+=Math.round(Math.random()*16).toString(16)
            }
            return col
        }

    </script>
</body>
</html>

6. Summary

In the process of learning canvas, we need to fully understand the drawing methods in the canvas element, and then practice more, so that we can know these methods clearly and use them without being unfamiliar. Without further ado, come and try it!

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JavaScript canvas realizes colorful sun halo effect

<<:  MySQL 5.7 zip archive version installation tutorial

>>:  How to view the IP address of the Docker container

Recommend

Native JS implements a very good-looking counter

Today I will share with you a good-looking counte...

Nginx anti-crawler strategy to prevent UA from crawling websites

Added anti-crawler policy file: vim /usr/www/serv...

Pure CSS to modify the browser scrollbar style example

Use CSS to modify the browser scroll bar style ::...

An example of refactoring a jigsaw puzzle game using vue3

Preface It took two days to reconstruct a puzzle ...

Detailed explanation of HTML page header code example

Knowledge point 1: Set the base URL of the web pa...

An Incomplete Guide to JavaScript Toolchain

Table of contents Overview Static type checking C...

Tutorial on installing mysql8 on linux centos7

1. RPM version installation Check if there are ot...

Tutorial on installing mysql5.7.18 on windows10

This tutorial shares the installation and configu...

MySQL deadlock routine: inconsistent batch insertion order under unique index

Preface The essence of deadlock is resource compe...

A brief discussion on whether MySQL can have a function similar to Oracle's nvl

Use ifnull instead of isnull isnull is used to de...

Detailed explanation of count without filter conditions in MySQL

count(*) accomplish 1. MyISAM: Stores the total n...

Calendar effect based on jQuery

This article example shares the specific code of ...

MySQL index coverage example analysis

This article describes MySQL index coverage with ...

Pure CSS3 realizes the effect of div entering and exiting in order

This article mainly introduces the effect of div ...

How to configure Nginx's anti-hotlinking

Experimental environment • A minimally installed ...