Basic use of canvas

Time:2020-4-1

Canvas can be used to make photo sets or animation of checkpoints, or even real-time video processing and rendering. Here I will introduce the simple use of canvas

1: Canvas label

The canvas tag and the IMG tag look very similar, Canvas has only two optional attributes, width and height. There are no SRC and ALT related attributes. If we don’t label canvas with width and height attributes, the default width is 300px and height is 150px. You can also use CSS attributes to set the width and height. However, if the width and height attributes are inconsistent with the initial scale, it will be distorted. Therefore, it is recommended that you never use the CSS attribute to set the width and height of the canvas label

Such as:

<canvas id="myCanvas" width="500" height="300"></canvas>

The canvas element itself has no drawing ability. All drawing work must be done inside JavaScript

1: Canvas initialization

Var canvas = document.getelementbyid ("mycanvas"); // know the canvas element  
Var CTX = canvas.getcontext ("2D"); // create context object

Because canvas is not supported in all browsers, here we can use the following methods to check the support

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
//Canvas related code

2: Simple use of canvas

1: Draw rectangle

Canvas provides three ways to draw rectangles

(1) : draw a filled rectangle

fillRect(x, y, width, height)  

(2) : draw a rectangular border

strokeRect(x, y, width, height)  

(3) : clears the specified rectangular area, and the area becomes completely transparent

clearRect(x, y, widh, height)  

Parameter Description:

x. Y: represents the coordinate (XY axis) of the upper left corner of the rectangle, which is equivalent to the coordinate origin of canvas

Width, height: indicates the width and height of the rectangle to be drawn

Such as:

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
//Canvas related code  
//Set the color of the rectangle  
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";  
//Draw filled rectangle  
ctx.fillRect (20, 20, 180, 80);  
//Draw a rectangular border  
ctx.strokeRect (10, 10, 200, 100);  
//Clears the specified rectangular area, and the area becomes completely transparent  
ctx.clearRect(50, 50, 120, 20)

According to the above phenomenon, it is as follows:

Basic use of canvas

2: Draw path

The basic element of a graph is a path, which is a collection of points of different shapes formed by connecting lines or curves of different colors and widths

The steps to draw a path in canvas are as follows:

(1) Create path start point

(2) Call the drawing method to draw the path

(3) Close the path

(4) Once the path is generated, the shape is rendered by tracing or filling the path area

To draw a path in canvas, you need to use the following methods:

(1) Create a new path. Once the path is created successfully, the drawing command is directed to the path to generate the path

ctx.beginPath()  

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

ctx.moveTo(x, y)  

(3) Closed path, draws a line from the current point to the starting point

ctx.closePath()  

(4) Drawing the outline of a figure by lines

ctx.stroke() 

(5) Fill the path content area to generate a solid drawing

ctx.fill()  

(6) Draw a line from the current point to the specified (x, y) coordinate

ctx.lineTo(x,y)  

An example of drawing path is as follows:

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
//Set fill area color  
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";  
ctx.beginPath()  
ctx.moveTo(20, 20)  
ctx.lineTo(200, 50);  
ctx.lineTo(200, 200);  
//Close the path and draw a path to the start point  
ctx.closePath();  
//Draw path  
ctx.stroke();  
//Fill closed area  
ctx.fill();

According to the above phenomenon, it is as follows:

Basic use of canvas

3: Draw an arc

There are two ways to draw arcs in canvas

(1) : arc method

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

Take (x, y) as the center and R as the radius, from startangle radian to endangle radian. Antilosewise is a Boolean value, true means counter clockwise, false means clockwise (the default is clockwise)

Here, the startangle and endangle parameters are in radians. The conversion between radians and degrees is as follows:

Radians = (math. Pi / 180) \ * degrees // angle converted to radians

And: when 180 ° is converted to radian, it is math.pi

Examples are as follows:

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
ctx.beginPath();  
//Draw an arc with the center coordinates of (50, 50), radius of 40, the actual radian of 0 (0 °), and the ending radian of 2 \ * math.pi (360 °)  
ctx.arc(50, 50,40,0,2\*Math.PI);  
ctx.stroke();  
ctx.beginPath();  
//Draw an arc with center coordinates of (150, 50), radius of 40, actual radian of 0 (0 °), ending radian of math.pi (180 °), and draw it anticlockwise  
ctx.arc(150, 50,40,0,Math.PI, true);  
ctx.stroke();  
ctx.beginPath();  
//Draw an arc whose center coordinates are (50, 150), radius is 40, and its radian is - math.pi/2 (- 90 °), and its ending radian is math.pi/2 (90 °). Draw it clockwise and fill in the content  
ctx.arc(50, 150, 40, -Math.PI / 2, Math.PI / 2, false);  
ctx.fill();  
ctx.beginPath();  
//Draw an arc with center coordinates of (150, 150), radius of 40, actual radian of 0 (0 °), and ending radian of math.pi (180 °), draw clockwise, and connect the starting point and ending point  
ctx.arc(150, 150, 40, 0, Math.PI, false);  
ctx.closePath();  
ctx.stroke();

According to the above phenomenon, it is as follows:

Basic use of canvas

(2) : arcto method

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

Draw an arc according to the given control point and radius, and then connect the two control points with a straight line

Examples are as follows:

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
ctx.beginPath();  
ctx.moveTo(50, 50);  
  //Parameter 1, 2: control point 1 coordinate parameter 3, 4: control point 2 coordinate parameter 4: arc radius  
ctx.arcTo(200, 50, 200, 200, 100);  
ctx.lineTo(200, 200)  
ctx.stroke();  
//Draw rectangle  
ctx.beginPath();  
ctx.rect(50, 50, 10, 10);  
ctx.rect(200, 50, 10, 10)  
ctx.rect(200, 200, 10, 10)  
ctx.fill()

According to the above phenomenon, it is as follows:

Basic use of canvas

Description of arcto method:

Arcto can be understood in this way. The arc you draw is determined by two tangents. Tangent 1: the line determined by the starting point and control point 1. Tangent 2: the line determined by control point 1 and control point 2. In fact, the arc drawn is the arc tangent to these two lines

4: Add styles and colors to canvas graphics

(1) Add color

Using fillStyle and strokestyle methods to add color to canvas graphics in canvas

Ctx.fillstyle = color // sets the fill color of the graphic  
CTX. Rokestyle = color // sets the color of the shape outline

Such as:

[1] Using the fillStyle method to set the fill color of a drawing

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
ctx.fillStyle = "rgba(0, 0, 200, 0.7)";  
ctx.fillRect (20, 20, 180, 80);

According to the above phenomenon, it is as follows:

Basic use of canvas

[2] Using strokestyle to add color to the shape outline

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
ctx.strokeStyle  = "rgba(0, 0, 200, 0.7)";  
ctx.strokeRect (20, 20, 180, 80);

According to the above phenomenon, it is as follows:

Basic use of canvas

(2) Set lineweight

Using linewidth to set the width of line segments in canvas

Such as:

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
ctx.beginPath();  
ctx.moveTo(10, 10);  
ctx.lineTo(100, 10);  
//Set line color  
ctx.strokeStyle = '#f00';  
//Set lineweight  
ctx.lineWidth = 10;  
ctx.stroke();

According to the above phenomenon, it is as follows:

Basic use of canvas

(3) Set line end style

In canvas, use linecap to set the end style of the line. There are three parameter values of linecap, namely:

But: the end of the segment ends with a square

Round: the end of the segment ends in a circle

Square: the end of the line segment ends with a square, but a rectangular area with the same width and half the thickness of the line segment is added

Examples are:

var canvas = document.getElementById("myCanvas");  
  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
//Set line color  
ctx.strokeStyle = 'rgba(0, 0, 200, 0.5)';  
//Set lineweight  
ctx.lineWidth = 20;  
  
ctx.beginPath();  
ctx.moveTo(10, 50);  
ctx.lineTo(10, 200);  
//Set line end style  
ctx.lineCap = 'butt'  
ctx.stroke();  
  
ctx.beginPath();  
ctx.moveTo(60, 50);  
ctx.lineTo(60, 200);  
//Set line end style  
ctx.lineCap = 'round'  
ctx.stroke();  
  
ctx.beginPath();  
ctx.moveTo(110, 50);  
ctx.lineTo(110, 200);  
//Set line end style  
ctx.lineCap = 'square'  
  
ctx.stroke();

According to the above phenomenon, it is as follows:

Basic use of canvas

(4) Set the style at the line junction

In canvas, use linejoin to set the style of the indirect joint of line and line. There are three parameters of linejoin, namely:

Round: draws the shape of the corner by filling an extra sector with the center of the circle at the end of the connected part. The radius of the fillet is the width of the segment.

Bevel: fill an extra triangle based area at the end of the connected part, each part has its own independent rectangular corner.

Miter: (default) forms an extra diamond area by extending the outer edge of the connected part so that it intersects at a point.

Examples are:

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d");  
//Set line color  
ctx.strokeStyle = 'rgba(0, 0, 200, 0.5)';  
//Set lineweight  
ctx.lineWidth = 10;  
ctx.beginPath();  
ctx.moveTo(10, 50);  
ctx.lineTo(50, 100);  
ctx.lineTo(80, 50);  
//Set line end style  
ctx.lineJoin = 'round'  
ctx.stroke();  
ctx.beginPath();  
ctx.moveTo(10, 100);  
ctx.lineTo(50, 150);  
ctx.lineTo(80, 100);  
//Set line end style  
ctx.lineJoin = 'bevel'  
ctx.stroke();  
ctx.beginPath();  
ctx.moveTo(10, 150);  
ctx.lineTo(50, 200);  
ctx.lineTo(80, 150);  
//Set line end style  
ctx.lineJoin = 'miter'  
ctx.stroke();

According to the above phenomenon, it is as follows:

Basic use of canvas

5: Draw dashed lines

Use the setlinedash method and the linedashoffset property in canvas to make the dashed line style. The setlinedash method takes an array to specify the alternation of line segments and gaps; the linedashoffset property sets the start offset

Such as:

var canvas = document.getElementById("myCanvas");  
  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d")  
CTX. Setlinedash (\ [20, 5 \]); // \ [solid line length, gap length \]  
Ctx.linedashoffset = - 0; // set offset  
//Set dashed line  
ctx.beginPath();  
ctx.moveTo(10, 10);  
ctx.lineTo(10, 100);  
ctx.stroke();  
//Set modesty rectangle border  
ctx.strokeRect (20, 10, 200, 100);

The phenomena are as follows:

Basic use of canvas

6: Draw text

Using filltext and stroketext methods to render text information in canvas

Filltext (text, x, y [, maxwidth]) fills the specified text in the specified (x, y) position, and the maximum width drawn is optional.

Stroketext (text, x, y [, maxwidth]) draws a text border at the specified (x, y) position. The maximum width drawn is optional.

Such as:

var canvas = document.getElementById("myCanvas");  
if (!canvas.getContext) {  
    Return 'does not support canvas'  
}  
var ctx=canvas.getContext("2d")  
//Set text border color  
ctx.strokeStyle = '#f00'  
//Set text fill color  
ctx.fillStyle = '#f00'  
//Set text style  
ctx.font = "100px sans-serif"  
//Set text information  
Ctx.filltext ("text information", 10, 100);  
Ctx.stroketext ("text message", 10, 200)

The phenomena are as follows:

Basic use of canvas

To set text information, we can also use the following properties to set the style of text information

Textalign = value text alignment option. Optional values include: start, end, left, right or center. The default is start.

Textbaseline = value baseline alignment option, optional values include: top, hanging, middle, alphabetic, ideographic, bottom. The default value is alpha..

Direction = value text direction. Possible values include: ltr, RTL, inherit. The default is inherit.

These are some basic uses of canvas