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

28 Famous Blog Redesign Examples

1. WebDesignerWall 2. Veerle's Blog 3. Tutori...

Install Linux rhel7.3 operating system on virtual machine (specific steps)

Install virtualization software Before installing...

Ubuntu20.04 VNC installation and configuration implementation

VNC is a remote desktop protocol. Follow the inst...

Grid systems in web design

Formation of the grid system In 1692, the newly c...

A simple example of MySQL joint table query

MySql uses joined table queries, which may be dif...

How to uninstall and reinstall Tomcat (with pictures and text)

Uninstall tomcat9 1. Since the installation of To...

In-depth explanation of the principle of MySQL Innodb index

introduction Looking back four years ago, when I ...

ReactRouter implementation

ReactRouter implementation ReactRouter is the cor...

How to dynamically modify the replication filter in mysql

MySQL dynamically modify replication filters Let ...

Native JS implementation of loading progress bar

This article shares a dynamic loading progress ba...

A brief discussion on mobile terminal adaptation

Preface The writing of front-end code can never e...

Take you to a thorough understanding of the prototype object in JavaScript

Table of contents 1. What is a prototype? 1.1 Fun...

wget downloads the entire website (whole subdirectory) or a specific directory

Use wget command to download the entire subdirect...