About the use of canvas (super detailed explanation of canvas knowledge system)

1. About canvas

1.1. Introduction

1.1.1. is new to HTML5, an HTML element that can draw images in it using scripts (usually JavaScript). It can be used to create photobooks or simple (not so simple) animations, and even do real-time video processing and rendering.

1.1.2. It was originally introduced by Apple internally using its own MacOS X WebKit for applications using widgets like Dashboard and the Safari browser. Later, it was proposed to use this element for the next generation of web technologies through Gecko-based browsers (especially Mozilla and Firefox), Opera and Chrome, and the Hypertext Web Application Technology Working Group.

1.1.3. Canvas is a drawable area defined by HTML code with height and width attributes. JavaScript code can access this area, similar to other common 2D APIs, through a complete set of drawing functions to dynamically generate graphics.

1.2. Precautions

1.2.1. canvas is a double label

1.2.2. If you do not set the width and height properties, the default width is 300 and height is 150, and the unit is px. You can also use css properties to set the width and height, but if the width and height properties are inconsistent with the initial ratio, it will be distorted. Therefore, it is recommended never to use css properties to set the width and height

1.2.3. Because some older browsers (especially IE browsers before IE9) or browsers do not support HTML elements, only alternative content can be displayed on these browsers.

2. Basic use of canvas

2.1. Rendering context

if(!canvas.getContext) return;

2.2. Detection support

if(!canvas.getContext) return;

2.3. Code Templates

<canvas id="tutorial" width="300" height="300"></canvas>
<script type="text/javascript">
function draw(){
    
    
	var canvas = document.getElementById('tutorial');
	if(!canvas.getContext) return;
	if(!canvas.getContext) return;
	ctx.fillStyle = "rgb(200,0,0)";
	//绘制矩形
	ctx.fillRect (10, 10, 55, 50);

	ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
	ctx.fillRect (30, 30, 55, 50);
}
draw();
</script>

3. Graphic drawing

3.1. Summary of methods

3.1.1. fillRect(x, y, width, height): Draw a filled rectangle

Parameter description: x, y: refer to the coordinates of the upper left corner of the rectangle. (relative to the coordinate origin of the canvas)

3.1.2. strokeRect(x, y, width, height): draw a rectangle border.

Same parameters as above

3.1.3. clearRect(x, y, width, height): Clear the specified rectangular area, and then this area will become completely transparent.

Same parameters as above

4. Path drawing

4.1. Basic steps

4.1.1. Create the starting point of the path

4.1.2. Call the drawing method to draw the path

4.1.3. Closing the path

4.1.4. Once the path is generated, render the shape by stroking or filling the path area.

4.2. Method Summary

4.2.1. beginPath()

Create a new path, once the path is successfully created, the graphics drawing command will be directed to the path to generate the path

4.2.2. moveTo(x, y)

Move the brush to the specified coordinates (x, y). Equivalent to setting the starting point coordinates of the path.

4.2.3. closePath()

After closing the path, graphics drawing commands are redirected to the context

4.2.4. stroke()

Draw the outline of the figure through the line

4.2.5. fill()

Generates a solid shape by filling the content area of ​​a path

4.2.6. lineTo(x,y)

Draws a line from the current position to the specified coordinates (x,y).

4.2.7. arc(x, y, r, startAngle, endAngle, anticlockwise)

Take (x, y) as the center and r as the radius, starting from startAngle radians to endAngle radians. anticlosewise is a boolean value, true means anticlockwise, false means clockwise (default is clockwise).

4.2.8. arcTo(x1, y1, x2, y2, radius)

Draw an arc according to the given control point and radius, and finally connect the two control points with a straight line, radius identifies the radius
example:
f078b3363dba1fd146a1093f2580d9443b8a4b03b7bbb883f4c919467229c34e.png

4.3. Bezier curve

4.3.1. A Bezier curve is actually a straight line

4.3.2. Quadratic Bézier curve

quadraticCurveTo(cp1x, cp1y, x, y)
parameter description: Parameters 1 and 2: control point coordinates, parameters 3 and 4: end point coordinates
Example diagram:
cfffc0506230c5c8a75ac6175785c4a46f8a97b52efcd2783557b9bd76e58fb2.png

4.3.3. Cubic Bezier curve

bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
parameter description: Parameters 1 and 2: coordinates of control point 1, parameters 3 and 4: coordinates of control point 2, parameters 5 and 6: coordinates of the end
point :
c7bc0abc00968469ca340f675d7075a68185f38f481689d6bfe8a0dec8a540d0.png

5. Style & Color

5.1. Basic method

5.1.1. fillStyle = color Set the fill color of the graphics

color can be a string of css color values, a gradient object or a pattern object

5.1.2. strokeStyle = color Set the color of the graphic outline

5.1.3. Transparency globalAlpha = transparencyValue

This property affects the transparency of all graphics in the canvas. Valid values ​​range from 0.0 (completely transparent) to 1.0 (completely opaque). The default is 1.0

5.1.4. lineWidth=1

line width. Can only be positive values. The default is 1.0.
The line connecting the start point and the end point is the center, and the upper and lower sides each account for half of the line width.

5.1.5. lineCap = type

butt: the end of the line segment ends with a square
round: the end of the line segment ends with a circle
square: the end of the line segment ends with a square shape, but a rectangular area with the same width as the line segment and half the thickness of the line segment is added.
examples:
58728eb5125088b216577578b4aa0702585453e2ebebc978c97b31173d45dbd2.png

5.1.6. lineJoin = type

round Draws the shape of the corner by filling an additional sector whose center is at the end of the connected part. The radius of the fillet is the width of the line segment.
bevel fills an additional triangle-based area at the end of connected parts, each with its own independent rectangular corner.
miter (default) forms an additional diamond-shaped region by extending the outer edges of connected parts so that they meet at a point.
examples:
9986b4ba8ae348e4ca0ec2184ab348d5a54b66084fdb87bb689daa54ec2b81dd.png

5.2. Dotted lines

5.2.1. setLineDash() method

Accepts an array to specify the alternation of line segments and gaps (e.g. ctx.setLineDash([20, 5]))

5.2.2. lineDashOffset property

Set the starting offset (eg ctx.lineDashOffset = -1)

5.2.3. getLineDash() Returns an array containing the current dashed line style, the length of which is a non-negative even number

6. Text drawing

6.1. Basic method

6.1.1. fillText(text, x, y [, maxWidth])

Fills the specified text at the specified (x,y) position, with optional maximum width drawn.

6.1.2. strokeText(text, x, y [, maxWidth])

Draws a text border at the specified (x,y) position, with an optional maximum width.

6.2. Text styles

6.2.1. font = value

The current style we use to draw text. This string uses the same syntax as the CSS font property. The default font is 10px sans-serif.

6.2.2. textAlign = value

Text alignment options. Possible values ​​include: start, end, left, right or center. The default value is start

6.2.3. textBaseline = value

Baseline alignment option, optional values ​​include: top, hanging, middle, alphabetic, ideographic, bottom. The default value is alphabetic.

6.2.4. direction = value

text direction. Possible values ​​include: ltr, rtl, inherit. The default value is inherit

7. Picture drawing

7.1. Note

Considering that the picture is loaded from the network, if the picture is not fully loaded when drawImage is executed, nothing will be done, and some browsers will throw an exception. So we should make sure to drawImage after the img is drawn

7.2. Drawing method templates

<img  src="图片路径" alt="" width="300"><br>
<canvas id="tutorial" width="600" height="400"></canvas>
function draw(){
    
    
	var canvas = document.getElementById('tutorial');
	if (!canvas.getContext) return;
	var ctx = canvas.getContext("2d");
	var img = document.querySelector("img");
	ctx.drawImage(img, 0, 0);
}

7.3. Detailed explanation of drawImage() method

7.3.1. Basic drawing: drawImage(img,x,y)

Parameter 1: the img to be drawn Parameter 2, 3: the coordinates of the drawn img in the canvas

7.3.2. Image scaling: drawImage(image, x, y, width, height)

Width and height, these two parameters are used to control the size that should be scaled when the canvas is drawn in

7.3.3. 切片:drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

The first parameter is the same as the others, which are references to an image or another canvas; 2-5 are to define the slice position and size of the image source, and 6-9 are to define the target display position and size of the slice
examples:
0732bb4b22d82f1488e61722d3c409709feca6a5a05bf91193c306a8658e395e.png

8. State saving and restoration

8.1. Description

State saving and restoration is a necessary operation for drawing complex graphics. Simply put, it is to draw a graphic and save it, and then continue to draw on the saved graphic until a target graphic is completed.

8.2. save() method

The Canvas state is stored in the stack, and whenever the save() method is called, the current state is pushed to the stack for saving

8.3. restore()

Every time the restore method is called, the last saved state is popped from the stack, and all settings are restored (similar to pop() of an array)

8.4. An example

function draw(){
    
    
	var canvas = document.getElementById('tutorial');
	if (!canvas.getContext) return;
	var ctx = canvas.getContext("2d");

	ctx.fillRect(0, 0, 150, 150);   // 使用默认设置绘制一个矩形
	ctx.save();                  // 保存默认状态

	ctx.fillStyle = 'red'       // 在原有配置基础上对颜色做改变
	ctx.fillRect(15, 15, 120, 120); // 使用新的设置绘制一个矩形

	ctx.save();                  // 保存当前状态
	ctx.fillStyle = '#FFF'       // 再次改变颜色配置
	ctx.fillRect(30, 30, 90, 90);   // 使用新的配置绘制一个矩形

	ctx.restore();               // 重新加载之前的颜色状态
	ctx.fillRect(45, 45, 60, 60);   // 使用上一次的配置绘制一个矩形

	ctx.restore();               // 加载默认颜色配置
	ctx.fillRect(60, 60, 30, 30);   // 使用加载的配置绘制一个矩形
}
draw();

examples:
2058c829f804b6c6902328c4c520aba5ce7a11b122005ba8efdc51f09ff4de02.png

9. Synthesis

9.1. Description

Through state saving and restoration, a complex graphic can be continuously superimposed on another graphic, but this is far from enough. Sometimes it is necessary to limit the drawing order, which can be achieved by compositing

9.2. Method: globalCompositeOperation = type

9.2.1. By default, the new image overwrites the old image

examples:
e3b73efdd1cfc7ebfd15e1d91f72b38f3b2c63efaa94d10bb42c2cd80f3fda4b.png

9.2.2. source-in will only show the overlapping part of the new image and the original image, and other areas will become transparent. (including other old image areas will also be transparent)

examples:
4e9c9e930b8d1a9a2045e09729b4a21ebb0d568e9617fdaa5b56948aedb3bce5.png

9.2.3. source-out Only display the part of the new image that does not overlap with the old image, and the rest of the image is transparent. (Old images are also not displayed)

examples:
65640ae00ca213540e223538597c3c1dd94d809dad51a91b71a9f34aded7590c.png

9.2.4. source-atop The new image only shows the area that overlaps with the old image. Old images can still be displayed.

examples:
9d066a7b5ad2934be86a0f133f51fcc6269a6074bde035264b011c1d55e41276.png

9.2.5. destination-over new image will be under the old image

examples:
507ee135ddee460317fff05f5ec494603fd349ece2c198d6a00b02bb1c2a7143.png

9.2.6. destination-in Only the old image in the overlapping part of the new and old images is displayed, and the other areas are all transparent.

examples:08128b8ea27a172acb87e0f373e5c64af3808fb3c488eecdca5d8f82605cb602.png

9.2.7. destination-out Only the parts of the old image that do not overlap with the new image. Note that some areas of the old image are shown.

examples:7bf0c20deaf6ba8866d8868dfcf858de4cefdb1b278fceac5754ffb75e33fd15.png

9.2.8. destination-atop The old image only shows the overlapping part, and the new image will be displayed below the old image

examples:030150c3897a77fed3b824d34da5e4b7986eeb868ad80ab9663194291b82173f.png

9.2.9. lighter Both old and new images are displayed, but the color of the overlapping area is processed.

examples:9a865ccf308aba2dfc21f2453f8d2ee0e44aaf8e633f76e25008e5d9a6eb5156.png

9.2.10. darken Keep the darkest pixel in the overlap. (each color bit is compared to get the smallest)

examples:833ebbd60e5be2d11cfbaca4d7842dbbc5fa2be6584431c0e841a1db815519fa.png

9.2.11. lighten Guarantees the maximum number of pixels in the overlap. (each color bit is compared, get the largest)

examples:9a865ccf308aba2dfc21f2453f8d2ee0e44aaf8e633f76e25008e5d9a6eb5156.png

9.2.12. xor overlapping parts will become transparent.

examples:f572382bb73773251594872c7ecc99b51946fdd601c80e7e1cc1fe8ae6818679.png

9.2.13. copy Only the new image will be kept, the rest will be cleared (transparent).

examples:ecb80bccd4e3730bcd4bdfc71657be44eb6004718116cf27c54c592586118ee8.png

10. Deformation

10.1. Method summary (basically the same as css3)

10.1.1. translate(x, y)

It is used to move the origin of the canvas to the specified position, x is the left and right offset, y is the up and down offset. It
is a good habit to save the state before doing deformation. In most cases, calling the restore method is much simpler than manually restoring the previous state. And if you are doing displacement in a loop without saving and restoring the state of the canvas, it is very likely that in the end you will find that something is missing, because it is likely to have exceeded the scope of the canvas

10.1.2. rotate(angle)

angle: the angle of rotation, it is clockwise, the value in radians, the center of rotation is the origin of coordinates

10.1.3. scale(x, y)

x, y are scaling factors for the horizontal and vertical axes respectively, and they must both be positive

11. Animation

11.1. Basic steps

11.1.1. Empty the canvas Before drawing each frame of animation, you need to clear everything. The easiest way to clear everything is the clearRect() method.

11.1.2. Saving the state of the canvas If the state of the canvas (color, moving the origin of coordinates, etc.) will be changed during the drawing process, and it is the original state when drawing each frame, it is best to save the state of the canvas

11.1.3. Drawing animation graphics This step is the real animation frame drawing

11.1.4. Restoring the canvas state If you saved the canvas state earlier, you should restore the canvas state after drawing a frame.

11.2. Common methods

11.2.1. setInterval()

11.2.2. setTimeout()

11.2.3. requestAnimationFrame()

11.3. A simple small case (dynamic code rain effect)

<!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>
<style>
* {
      
      
	margin: 0;
	padding: 0;
	overflow: hidden;
}
</style>
</head>

<body>
	<canvas id="bg"></canvas>
<script>
	// 获取对象
	const cvs = document.getElementById("bg");
	// 设置canvas画布宽高
	const width = window.innerWidth;
	const height = window.innerHeight;
	cvs.width = width;
	cvs.height = height;
	// 返回一个用于在画布上绘图的环境
	const ctx = cvs.getContext("2d");
	// 定义每列的宽度
	const columnWidth = 20;
	// 生成的列数
	const columnCount = Math.floor(window.innerWidth / columnWidth)
	// 创建数组
	const columnNextIndexes = new Array(columnCount);
	// 全部用1填充
	columnNextIndexes.fill(1);
	// 绘画
	function draw() {
      
      
		// 背景颜色
		ctx.fillStyle = 'rgba(240,240,240,0.2)';
		// fillRect(x1, y1, width, width) 画图形
		ctx.fillRect(0, 0, width, height);
		// 设置颜色
		ctx.fillStyle = getRandomColor();
		const fz = 20;
		// 字体样式
		ctx.font = `${ 
        fz}px Calibri`;
		for (let i = 0; i < columnCount; i++) {
      
      
			// x坐标
			const x = i * columnWidth;
			// y坐标
			const y = fz * columnNextIndexes[i];
			// 填充内容
			ctx.fillText(getRandomChar(), x, y);
			// 判断是否超出可视范围
				if (y > height && Math.random() > 0.99) {
      
      
					columnNextIndexes[i] = 0;

				} else {
      
      
					columnNextIndexes[i]++
			}
		}
	}
	draw()
	setInterval(draw, 40)
	// 随机颜色
	function getRandomColor() {
      
      
		const fontColor = [
			"#33b5e5",
			"#0099cc",
			"#aa66cc",
			"#9933cc",
			"#669900",
			"#ffbb33",
			"#ff8800",
			"#ff4444",
			"#cc0000"
		]
		return fontColor[Math.floor(Math.random() * fontColor.length)]
	}
	// 随机字符
	function getRandomChar() {
      
      
		const str = "console.log('hello world')";
		return str[Math.floor(Math.random() * str.length)]
	}
</script>
</body>

</html>

Guess you like

Origin blog.csdn.net/adminsir0/article/details/131092135