Summary of the use of the Canvas element in HTML5

Summary of the use of the Canvas element in HTML5

    Canvas provides an interface for developers to customize drawing. We can use the getContext() function of the principality to obtain the drawing context for drawing operations. Two parameters can be passed in this function. The first parameter sets the type of drawing context, which is more commonly used. is "2d", we can also use "webgl" to achieve 3D drawing using webOpenGL. This blog mainly summarizes the related methods of 2d rendering.

1. Do simple graphic drawing

    Drawing flat graphics using Canvas is relatively simple. For example, using the following function can directly draw a rectangular area.

		var c = document.getElementById("canvas");
		var context = c.getContext("2d");
		context.strokeRect(20,20,100,100);

The graphic effect is as follows:

Corresponding to strokeRect, use fillRect to draw a filled rectangle, for example:

		var c = document.getElementById("canvas");
		var context = c.getContext("2d");
		context.fillRect(20,20,100,100);

The effect is as follows:

Use the clearRect function to erase the rectangular area. The example is as follows:

		var c = document.getElementById("canvas");
		var context = c.getContext("2d");
		context.strokeRect(20,20,100,100);
		context.clearRect(10,10,100,100);

The effect is as follows:

The above method of drawing graphics is actually a composite function, which completes two steps of path definition and drawing. We can also customize the graphics path, for example:

		var c = document.getElementById("canvas");
		var context = c.getContext("2d");
		context.beginPath();
		context.moveTo(20,20);
		context.lineTo(20,100);
		context.lineTo(100,100);
		context.closePath();
		context.stroke();

The effect is as follows:

The beginPath function is used to open a path, the moveTo function is used to move the brush to a certain point, and the lineTo function is used to define a line. The starting point of the line is the position of the current brush, and the parameter is the end position. The closePath function is used to close the path. Of course, this function does not have to be called. If it is not called, non-closed graphics can be drawn. The stroke function is used to draw the defined graphics, and correspondingly there is a fill function used to fill and draw.

    The quadraticCurveTo and bezierCurveTo functions are used to create quadratic and cubic Bezier curve paths, respectively. Examples are as follows:

		context.moveTo(20,120);
		context.quadraticCurveTo(20,200,100,180);
		context.stroke();
		context.moveTo(20,200);
		context.bezierCurveTo(20,300,60,300,60,200);
		context.stroke();

The effect is as follows:

For related content about Bezier curves, you can check the following blogs:

https://my.oschina.net/u/2340880/blog/1519503

The arc function is used to create circular arcs, for example:

        context.moveTo(110,350);
		context.arc(60,350,50,0,2*Math.PI,false);
		context.stroke();

In the arc function, the first two parameters set the center point of the circle, the third parameter sets the radius, the fourth and fifth parameters set the starting point and ending point of the arc, expressed in radians, and the last parameter is a Boolean value. Set whether to draw in reverse. There is also an arcTo function to draw an arc between two tangents, as follows:

		context.moveTo(20,420);
		context.arcTo(80,420,80,600,50);
		context.stroke();

Results as shown below:

Use the clip function to perform clipping operations. After clipping, subsequent drawing can only be drawn in the clipped area, for example:

		context.rect(0,500,100,30);
		context.clip();
		context.fillRect(0,500,200,200);

The effect is as follows:

One thing to note, after using the clip function to clip, the subsequent drawing will only be drawn within the clipped area. If you want to draw outside the clipped area, you need to use the save and restore functions to process it. Before clipping, use The save function is used to save the state of the current drawing context. When you want to draw outside the clipping area, use the restore function to restore the drawing context.

2. Draw text and images

    The previous example shows the use of Canvas to draw graphics. In addition to graphics, images and text can also be easily drawn using Canvas. Use the drawImage function to draw the image, as follows:

        var image = document.createElement("img");
		image.src = 'img/HBuilder.png';
		image.onload = function(){
				context.drawImage(image,0,600);
		}

It should be noted that after the img element is created above, the rendering cannot be performed immediately after setting the src attribute, because the loading of the image takes time, and the image data cannot be obtained by direct rendering. The drawImage function can have a total of 8 parameters, drawImage(img,sx,sy,sw,sh,x,y,w,h). Among them, sx, sy, sw, and sh are used to crop the original image, and only select parts of the image for drawing. x, y, w, and h set the coordinates and dimensions of the drawing on the canvas.

    Regarding text drawing, you can use the fillText or strokeText functions, which are used to draw solid and hollow text, respectively. An example is as follows:

        context.font = "20px Georgia";//设置字体
 		context.textAlign = 'start';  //设置文字对齐方式
		context.fillText("Hello World",0,750,200);
		context.strokeText("Hello World",0,800,200);

The effect is as follows:

3. Setting of drawing properties

    During the drawing process, the developer can set the drawn line color, fill color, style, shadow, etc. An example is as follows:

		context.fillStyle = 'red';  //设置填充颜色
		context.strokeStyle = 'blue'; //设置线条颜色
		context.shadowColor = 'green'; //设置阴影颜色
		context.shadowBlur = 10;   //设置阴影模糊度
		context.shadowOffsetX = 10; //设置阴影X轴偏移量
		context.shadowOffsetY = 5;  //设置阴影Y轴偏移量
		context.lineCap = 'round';  //设置线帽样式
		context.lineJoin = 'round'; //设置折点样式
		context.lineWidth = 1; //设置线条宽度

The effect is as follows:

The two properties of fillStyle and strokeStyle are special. From the name, it can be understood that they are used to set the style of the fill or line. Setting the color is only one way. It can also be set as a gradient object to achieve gradient effects. E.g:

		var g = context.createLinearGradient(0,750,200,750);
		g.addColorStop(0,'black');
		g.addColorStop(0.5,'red');
		context.fillStyle =  g;
		context.fillText("Hello World",0,750,200);

The effect is as follows:

The createLinearGradient function is used to create a linear gradient layer, where 4 parameters set the x, y of the starting point and the x, y of the ending point. Call the addColorStop function to add critical points and color values ​​to the gradient layer. Divergent gradients can also be created, for example:

        var g = context.createRadialGradient(70,800,20,70,800,50);
		g.addColorStop(0,'black');
		g.addColorStop(1,'red');
		context.fillStyle =  g;
		context.fillRect(20,750,100,100);

The effect is as follows:

The first 3 parameters of the createRadiaGradient function set the arc at the beginning of the gradient (set the center x, y coordinates and radius respectively), and the last 3 parameters set the arc at the end of the gradient (set the center x, y coordinates and radius respectively).

    fillStyle and strokeStyle can also be set to a pattern background, such as the background obtained by repeating the image, for example:

        image.onload = function(){
			var p = context.createPattern(image,'repeat');
		    context.fillStyle =  p;
			context.fillRect(20,750,200,200);
		}

Results as shown below:

Optional repeat patterns are also:

repeat-x: Repeat only horizontally.

repeat-y: Repeat vertically only.

no-repeat: No repeat, only displayed once.

4. Do canvas transformation

    The canvas can also perform some simple transformation operations, such as rotation, scaling and so on. It should be noted that operations on the canvas will not affect the content already drawn on the canvas, and the content drawn later will be affected. Use the scale(x,y) function to scale the canvas, where the two parameters x and y set the horizontal and vertical scaling ratios respectively. The rotate(angle) function is used to rotate the canvas, where the parameter is the rotation angle value. The translate(x,y) function is used to translate the canvas. The parameters x and y set the translation amount in the horizontal and vertical directions respectively. There is also a composite transform(a,b,c,d,e,f) function, which can be used to set translation, rotation and scaling properties in one step. The meaning of the parameters is as follows:

a: Set the horizontal zoom ratio

b: set horizontal tilt

c: set vertical tilt

d: Set the vertical zoom ratio

e: set horizontal pan

f: set vertical pan

It should be noted that if you call transform multiple times, each transform will be performed on the basis of the previous one. If you don't want to keep the last record, you can call the setTransform() function to reset the settings.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325431842&siteId=291194637