js implements clock component based on canvas

js implements clock component based on canvas

Canvas has always been an indispensable tag element for drawing graphics in front-end development, such as compressed uploaded pictures, scratch cards, poster making, chart plug-ins, etc. Many people will be asked during the interview process whether they have ever been exposed to canvas graphics drawing.

definition

The canvas element is used to draw graphics, which is done through scripts (usually JavaScript).
The canvas tag is just a graphics container, you have to use scripts to draw the graphics.

Browser support

Internet Explorer 9, Firefox, Opera, Chrome and Safari support

This article will use a clock component to familiarize yourself with the canvas API.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>canvas clock</title>
<style>
*{margin:0;padding:0;}
body{text-align:center;padding-top:100px;}
</style>
</head>
<body>
<canvas id="clock" width="200px" height="200px"></canvas>
<script>
(function (win) {
	function DrawClock(options){
		this.canvas = options.el;
		this.ctx = this.canvas.getContext('2d'); //The method returns an environment for drawing on the canvas this.width = this.ctx.canvas.width;
		this.height = this.ctx.canvas.height;
		this.r = this.width / 2;
		this.rem = this.width / 200;
		this.digits = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];

	  var self = this;
	  self.init();
	  setInterval(function(){
	  	self.init();
	  }, 1000);
	}

	DrawClock.prototype = {
		init: function(){
			var ctx = this.ctx;
			ctx.clearRect(0, 0, this.width, this.height); //Clear the specified pixels in the given rectangle var now = new Date();
			var hours = now.getHours();
			var minutes = now.getMinutes();
			var seconds = now.getSeconds();

			var hour = hours >= 12 ? hours - 12 : hours;
			var minute = minutes + seconds / 60;

			this.drawBackground();
			this.drawHour(hour, minute);
			this.drawMinute(minute);
			this.drawSecond(seconds);
			this.drawDot();
			ctx.restore();
		},
		drawBackground: function(){
			var ctx = this.ctx;
			var self = this;
			ctx.save();
			ctx.translate(this.r, this.r); //Remap the (0,0) position on the canvas ctx.beginPath();
			ctx.lineWidth = 8 * this.rem;
			ctx.arc(0, 0, this.r - ctx.lineWidth / 2, 0, 2 * Math.PI, false); //Create an arc/curve (used to create a circle or partial circle)
			ctx.stroke();
			ctx.font = 16 * this.rem + "px Arial"; //Set or return the current font properties of the text content ctx.textAlign = "center"; //Set or return the current alignment of the text content ctx.textBaseline = "middle"; //Set or return the current text baseline used when drawing text this.digits.forEach(function(number, i){
				var rad = 2 * Math.PI / 12 * i;
				var x = Math.cos(rad) * (self.r - 33 * self.rem);
				var y = Math.sin(rad) * (self.r - 33 * self.rem);
				ctx.fillText(number, x, y); //Draw the "filled" text on the canvas });

			//Minute scale, 6 degrees per minute
			for (var i = 0; i < 60; i++){
				ctx.save(); //Save the state of the current environment ctx.rotate(6 * i * Math.PI / 180); //Rotate the current drawing ctx.beginPath(); //Start a path, or reset the current path ctx.moveTo(0, -82 * this.rem); //Move the path to the specified point in the canvas without creating a line ctx.lineTo(0, -87 * this.rem); //Add a new point, and then create a line from that point to the last specified point in the canvas ctx.closePath(); //Create a path from the current point back to the starting point ctx.strokeStyle = '#000'; //Set or return the color, gradient, or mode used for the stroke ctx.lineWidth = 1 * this.rem; //Set or return the current line width ctx.stroke(); //Draw a defined path ctx.restore(); //Return the previously saved path state and properties }
			//Hour scale, rotate 30 degrees every hour
			for (var i = 0; i < 12; i++){
				ctx.save();
				ctx.rotate(30 * i * Math.PI / 180);
				ctx.beginPath();
				ctx.moveTo(0, -79 * this.rem);
				ctx.lineTo(0, -87 * this.rem);
				ctx.closePath();
				ctx.strokeStyle = '#000';
				ctx.lineWidth = 2 * this.rem;
				ctx.stroke();
				ctx.restore();
			}
		},
		drawHour: function(hour, minute){
			var ctx = this.ctx;
			ctx.save();
			ctx.beginPath();
			var hRad = 2 * Math.PI / 12 * hour;
			var mRad = 2 * Math.PI / 12 / 60 * minute;
			ctx.rotate(hRad + mRad);
			ctx.lineWidth = 6 * this.rem;
			ctx.lineCap = "round"; //Set or return the end point style of the line ctx.moveTo(0, 10 * this.rem);
			ctx.lineTo(0, -this.r / 2);
			ctx.stroke();
			ctx.restore();
		},
		drawMinute: function(minute){
			var ctx = this.ctx;
			ctx.save();
			ctx.beginPath();
			var rad = 2 * Math.PI / 60 * minute;
			ctx.rotate(rad);
			ctx.lineWidth = 3 * this.rem;
			ctx.lineCap = "round";
			ctx.moveTo(0, 10 * this.rem);
			ctx.lineTo(0, -this.r + 26 * this.rem);
			ctx.stroke();
			ctx.restore();
		},
		drawSecond: function(second){
			var ctx = this.ctx;
			ctx.save();
			ctx.beginPath();
			ctx.fillStyle = "#c14543";
			var rad = 2 * Math.PI / 60 * second;
			ctx.rotate(rad);
			ctx.moveTo(-3 * this.rem, 20 * this.rem);
			ctx.lineTo(3 * this.rem, 20 * this.rem);
			ctx.lineTo(1, -this.r + 26 * this.rem);
			ctx.lineTo(-1, -this.r + 26 * this.rem);
			ctx.fill(); //Fill the current drawing (path)
			ctx.restore();
		},
		drawDot: function(minute){
			var ctx = this.ctx;
			ctx.beginPath();
			ctx.fillStyle = "#fff";
			ctx.arc(0, 0, 3 * this.rem, 0, 2 * Math.PI, false);
			ctx.fill();
		}
	};

    win.DrawClock = DrawClock;
})(window);

new DrawClock({el: document.getElementById("clock")});
</script>
</body>
</html>

As long as you have hills and valleys in your mind, you can cultivate two acres of land! The canvas clock uses most of the APIs in canvas. By learning the code implementation of the canvas clock, you can understand the properties and methods of canvas. At the same time, when realizing the clock effect, the geometric models of sine, cosine and radian calculation methods in mathematics are used, and the fun of learning mathematics in the past is relived. It can be said to kill two birds with one stone.

The clock effect diagram is as follows:

The above is the details of how to implement the clock component based on canvas in js. For more information about the clock component implemented by canvas, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript canvas text clock
  • Using js and canvas to realize clock effect
  • JavaScript canvas animation to achieve clock effect
  • JavaScript Canvas writes a colorful web clock
  • JavaScript + HTML5 canvas drawing clock function example
  • JS+H5 Canvas to achieve clock effect
  • JS+Canvas draws dynamic clock effect
  • JavaScript Canvas draws a circular clock effect
  • js Canvas draws a circular clock effect
  • Calendar clock case sharing implemented by js Canvas
  • js Canvas realizes circular clock tutorial

<<:  Super detailed steps to install zabbix3.0 on centos7

>>:  A brief discussion on mysql backup and restore for a single table

Recommend

How to solve the phantom read problem in MySQL

Table of contents Preface 1. What is phantom read...

Detailed explanation of how to use WeChat mini program map

This article example shares the specific implemen...

Ubuntu starts the SSH service remote login operation

ssh-secure shell, provides secure remote login. W...

CSS3 achieves flippable hover effect

CSS3 implements a flippable hover effect. The spe...

How to pop up a temporary QQ dialog box to chat online without adding friends

In fact, this is very simple. We add an a tag to ...

Detailed explanation of MySQL database triggers

Table of contents 1 Introduction 2 Trigger Introd...

A brief discussion on the role of HTML empty links

Empty link: That is, there is no link with a targ...

JavaScript realizes the effect of mobile modal box

This article example shares the specific code of ...

Tutorial on how to install htop on CentOS 8

If you are looking to monitor your system interac...

How to monitor Tomcat using LambdaProbe

Introduction: Lambda Probe (formerly known as Tom...

The iframe frame sets the white background to transparent in IE browser

Recently, I need to frequently use iframe to draw ...

How does Vue track data changes?

Table of contents background example Misconceptio...

Several ways of running in the background of Linux (summary)

1. nohup Run the program in a way that ignores th...