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

Comprehensive summary of mysql functions

Table of contents 1. Commonly used string functio...

Draw an iPhone based on CSS3

Result:Implementation Code html <div class=...

Some understanding of absolute and relative positioning of page elements

From today on, I will regularly organize some smal...

The order of event execution in the node event loop

Table of contents Event Loop Browser environment ...

Detailed steps to install nginx on Apple M1 chip and deploy vue project

brew install nginx Apple Mac uses brew to install...

Beginners understand MySQL deadlock problem from source code

After many difficult single-step debugging late a...

Two implementation codes of Vue-router programmatic navigation

Two ways to navigate the page Declarative navigat...

Summary of examples of common methods of JavaScript arrays

Table of contents Common array methods concat() M...

JavaScript to achieve mouse drag effect

This article shares the specific code of JavaScri...

Overview of the definition of HTC components after IE5.0

Before the release of Microsoft IE 5.0, the bigges...

Add a startup method to Linux (service/script)

Configuration file that needs to be loaded when t...

Implementation of CSS border length control function

In the past, when I needed the border length to b...

A brief discussion on Nginx10m+ high concurrency kernel optimization

What is high concurrency? The default Linux kerne...

Docker-compose installation db2 database operation

It is troublesome to install the db2 database dir...