- The Canvas element itself has no drawing ability, so all drawing work must be done inside JavaScript. var cv = document.getElementById(“myCanvas”); var context = cv.getContext(“2d”); // Apply for an environment to draw 2D animations
- Check whether the browser supports it: you can also check if(Canvas.getContext) with javascript.
If it is not supported, you can insert an unsupported message into the canvas tag text.
The < canvas > hey! Your current browser does not support Canvas canvas. Please update your browser. </canvas>Copy the code
- General drawing examples
-
Draw a line with canvas (a) context.moveTo(starting point x, starting point Y) (b) context.lineTo(ending point x, ending point Y) : Draw a line from the starting point provided by moveTo to the coordinates of the lineTo; Without moveTo, lineTo is the equivalent of moveTo. If a lineTo is added after a lineTo, the line extends from the coordinates of the previous lineTo to the next lineTo. (c) context.stroke() : Draws a line at the given coordinates. You can also specify the style of the line, the thickness of the color, etc.
-
FillRect (x, y, width, height) : fillRect(x, y, width, height) : StrokeStyle = “color” : border color (b) context. StrokeRect (starting point X, starting point Y, width, height) : Stroke only, no fill
-
Draw a circle with canvas (a) context.fillStyle = “color”; (c) context.arc(center of the circle x, center of the circle y, radius, start Angle, end Angle, is drawn clockwise according to the given start Angle and end Angle) where: The starting Angle is 0, and the ending Angle is 0.5 PI (directly below),1 PI and 1.5 PI (directly above), providing a basis for the pie chart to be drawn. Math.pi *2 is the entire circle, math.pi is the semicircle (d) context.closepath () : (e) context.fill() : fills the graph, and sometimes uses context.stroke() instead
Example:
for(var i = 0; i<=15; i++){ context.beginPath(); context.arc(150.150,i*10.0.Math.PI*0.5.true); // Start at 0 and end clockwise math.pi *0.5, that is, right below the circle
context.stroke(); // Draw only borders without padding
}
Copy the code
for(var i = 0; i<=15; i++){ context.beginPath(); context.arc(150.150,i*10.0.Math.PI*1.true);// Start at 0 and end clockwise math.pi, that is, end the semicircle directly below the circle
context.stroke(); // Draw only borders without padding
}
Copy the code
for(var i = 0; i<=15; i++){ context.beginPath(); context.arc(150.150,i*10.0.Math.PI*1.5.true);// Start at 0 and end clockwise math. PI*1.5, that is, right above the circle
context.stroke(); // Draw only borders without padding
}
Copy the code
for(var i = 0; i<=15; i++){ context.strokeStyle ="red"; // Set the border color
context.beginPath();
context.arc(150.150,i*10.0.Math.PI*2.true);
context.stroke(); // Draw only borders without padding
}
Copy the code
- Draw triangles with canvas
- // Hollow triangle
context.beginPath(); // Start drawing paths
context.moveTo(100.100); // Set the starting point to (100,100)
context.lineTo(150.150); // Set the next point to (150,150)
context.lineTo(50.150); // set the next point to (50,150)
context.closePath();// connect the starting point and the ending point
context.stroke(); // Draw lines
Copy the code
- // Solid triangle
context.fillStyle = "red"; // Set the fill color
context.moveTo(150.50); // set the starting point to (150,50)
context.lineTo(250.250);// Set the next point to (150,150)
context.lineTo(50.250);// set the next point to (50,150)
context.fill(); // Fill the color, because it fills the entire image, so it can have closePath() or not
Copy the code
- // Clear the canvas [or part of it]
context.fillStyle = "red";
context.moveTo(150.50);
context.lineTo(250.250);
context.lineTo(50.250);
context.closePath();
context.fill();
var clearBtn = document.getElementById("clearCanvas");
clearBtn.onclick=function(){
context.clearRect(0.0.150.300); // Clear part of the canvas pattern
// context.clearrect (start x, start y, canvas width, canvas height); If the width and height are the same as the size of the entire canvas, the entire canvas is cleared
};
Copy the code
- Draw a quadratic Bezier curve
context.strokeStyle = "black"; // Set the line color
context.beginPath(); // Start drawing
context.moveTo(0.200); // define the starting point, starting from (0,200)
/ / context. QuadraticCurveTo (x x, control point y, end point, end point y),
QuadratciCurveTo (150,100,300,200); // the control point is the intersection of its two lines with the start and end coordinates.
context.stroke(); // Draw lines
context.globalCompositeOperation = "source-over";
/ / globalCompositeOperation attributes are used for graphics, which will be a source (new) mapped to the target image (existing) image.
// Source image = the drawing you want to place on the canvas. Target image = a drawing that you have placed on the canvas.
// Source image: ↓(Quadratic Bezier curve is drawn according to the straight line part)
context.strokeStyle = "red";
context.beginPath();
context.moveTo(150.100);
context.lineTo(0.200);
context.moveTo(150.100);
context.lineTo(300.200);
context.stroke();
Copy the code
- Cubic bezier curve drawing (bezierCurveTo) reference to understand: https://blog.csdn.net/cdnight/article/details/48468653
context.strokeStyle = "black";
context.beginPath(); // Start drawing
context.moveTo(0.200); // draw from (0,200)
context.bezierCurveTo(25.50.75.50.300.200);
//context.bezierCurveTo(control point 1 x, control point 1 y, control point 2 x, control point 2 2, end point x, end point y)
context.bezierCurveTo(25.50.75.50.300.200);
context.stroke();
context.globalCompositeOperation = "source-over";
context.strokeStyle = "red";
context.beginPath();
// The line from control point 1 to the starting point
context.moveTo(25.50);
context.lineTo(0.200);
// From control point 1 to control point 2
context.moveTo(25.50);
context.lineTo(75.50);
// Control point 2 to end point line
context.moveTo(75.50);
context.lineTo(300.200);
context.stroke();
Copy the code
-
The image of Canvas can be saved in stack mode according to the current state and restored according to the last state. Save: : to save the state of Canvas. After save, operations such as translation, scaling, rotation, miscutting and clipping of Canvas can be called. B. restore: Used to restore the previously saved state of the Canvas. Prevent operations performed on Canvas after save from affecting subsequent drawing. Note: Save represents the state before the save function is saved, and restore represents the state before the save function is retrieved
Example:
// Rectangle 1, fill with orange and border with red
context.fillStyle = "orange";
context.strokeStyle = "red";
context.fillRect(20.20.100.100);
context.strokeRect(20.20.100.100);
context.fill();
context.stroke();
// Keep the current canvas state
context.save();
// Draw rectangle two with yellow fill color and pink border color
context.fillStyle="yellow";
context.strokeStyle="pink";
context.fillRect(150.20.100.100);
context.strokeRect(150.20.100.100);
context.fill();
context.stroke();
// Restore the state of the previous rectangle to paint
// context.restore();
context.fillRect(20.150.100.100);
context.strokeRect(20.150.100.100);
Copy the code
↓ : The last painting style is saved. Context
↓ : Saves the painting style of context.save()
8. Move the coordinate space and draw the gradient umbrella effect. By default, the top left corner of the canvas is the origin of the coordinates. The unit of coordinate space is pixels. When drawing an image, you can use Translate to move the coordinate space so that the origin of the coordinate space is moved to a specified position.
Example:
var canvasMethod = {
drawTop:function(context,fillColor){
context.fillStyle = fillColor;
context.strokeStyle = fillColor;
context.beginPath();
// start at 0,0 and draw a square with a radius of 30 pixels
context.arc(0.0.30.0.Math.PI,true);
context.closePath();
context.fill();
context.save();// Save the current state of the canvas, move the position, fillStyle,strokeStyle is fillColor
},
drawStick:function(context){
context.fillRect(1.5.0.1.40);// Draw a rectangle, but the rectangle is actually a line with a left offset of 1.5 pixels, a width of 1 and a height of 40, and fill it with the style shown in Save
context.beginPath();
context.strokeStyle = "blue";
context.arc(- 5.40.4.Math.PI,Math.PI*2.true);// The center of the circle is (-5,40), the radius is 4, and it follows the direction from PI to 2PI.
context.restore();// Use the canvas style in save, that is, fillStyle,strokeStyle is fillColor
context.stroke();Stroke according to the style of save
},
printUmbrella:function(){
var context = document.getElementById("canvas1").getContext("2d");
context.translate(80.80);// move the origin to (80,80) for the first time
// Draw ten umbrellas
for (var i = 0; i < 10; i++) {
context.save();// Save the previous state of the canvas, move the position, fillStyle,strokeStyle defaults to black
context.translate(60*i,0);// Keep changing the origin of the coordinates to the right 60 pixels at a time
this.drawTop(context,"rgb("+ (30*i)+","+ (255- 30*i)+", 255).");// Draw the semicircle and change the fill color
this.drawStick(context);// Draw the umbrella handle
context.restore();// Use the canvas save Settings, move the position, fillStyle,strokeStyle defaults to black}}};window.onload = function(){
canvasMethod.printUmbrella();
}
Copy the code
9. Rotate coordinate space
The rotate() method specifies an Angle that changes the mapping between the Canvas coordinates and the pixels of the Canvas element in the Web browser so that any subsequent drawing appears rotated in the Canvas. But it doesn’t rotate the Canvas element itself. There is only one parameter, which is the Angle of rotation. Then on a umbrella example, change canvasMethod printUmbrella () method.
printUmbrella:function(){
var context = document.getElementById("canvas1").getContext("2d");
context.translate(150.150);// Move the origin to (150,150) for the first time
// Draw 8 umbrellas
for (var i = 0; i < 8; i++) {
context.save();// Save the last movement of the canvas
context.rotate(Math.PI*0.25*i); //2PI/8=0.25PI, each rotation is 0.25PI
context.translate(0.- 100.);// Keep changing the origin of the coordinates, moving up 100 pixels at a time
this.drawTop(context,"rgb("+ (30*i)+","+ (255- 30*i)+", 255).");// Draw the semicircle and change the fill color
this.drawStick(context);// Draw the umbrella handle
context.restore();// Use the canvas save setting}}Copy the code
10. Scale the figure
The canvas uses scale() to change the number of horizontal and vertical pixels in the Canvas context to change the size of the graph.
The two parameters received are respectively the x axis scaling factor and y axis scaling factor, both of which must be positive. If larger than the original, it is >1; if smaller than the original, it is <1. For example, passing a value of 2.0 and 0.5 will cause the plot path to be twice as wide and half as tall.
Example:
function scaleCircle(context){
context.translate(250.20);
for (var i = 0; i < 80; i++) {
context.save(); // Save the Settings of the previous canvas
context.translate(30.30);// each iteration moves the new origin to (30,30)
context.scale(0.95.0.95);// The vertical and horizontal factors are reduced to 0.9 times in each iteration
context.rotate(Math.PI/12)/ / rotation
context.beginPath();// Start drawing
// context.fillStyle = "red";
/ / the context. GlobalAlpha = "0.4"; // Set the color transparency
context.fillStyle= "Rgba (155, 187, 89, 0.7)";
context.arc(0.0.50.0.Math.PI*2.true);/ / draw circlecontext.closePath(); context.fill(); }}window.onload = function(){
scaleCircle(context);
}
Copy the code
11. Matrix transformation
A quote from understanding the site: http://jo2.org/html5-canvas-transform/
Each time a canvas context object generates an image, a corresponding matrix object will be created. The Canvas deformation matrix can be directly modified, and the graph can be moved, rotated, sliced and reflected through matrix transformation.
So the question is: what is the default matrix for a graph that has a matrix? The answer is,0,0,1,0,0: (1).
① Why not all zero? A graph without scaling, rotation, or displacement will also have a property of 1: scale! Because without scaling, the scale of the graph is actually double the original size. That’s why there are two 1’s in the default matrix. So the 1 at position 1 represents the scale on the x axis, and the 1 at position 4 represents the scale on the y axis! Transform (scaleX,0,0,scaleY,0,0); To set the effect.
② According to the graph default matrix, the last two parameters in the matrix are the number representing the displacement distance (0 in the case of no displacement). I.e., the mobile can be based on: context. The transform (scaleX, 0, 0, scaleY, transX, transY); To set the effect.
③ Do the remaining two numbers (parameter position 2, parameter position 3) indicate rotation? No, they mean tangent. What is a diagonal cut? A diagonal cut is made by pulling on either side of a rectangle to form a parallelogram. Example:
Arc (200,50,50,0, math.pi *2).fillrect (200,100,50,50).stroke()Copy the code
Arc (200,50,w/2,0, math.pi *2) . FillRect,50,50 (200100). The stroke ()Copy the code
So in this code we can see that we’re using a tan function, and if we want to make a tangent cut, if we want to make a tangent cut of 30 degrees, then we have to wrap the tangent of 30 degrees,x/y.
Graphics can be understood as a matrix of the CTX. Transform (scaleX, skewX skewY, scaleY, transX, transY); New coordinate x’ = (scaleX)x + (skewY)y + transX New coordinate y’ = (skewX)x + (scaleY)y + transY
④ How to use transform to transform graphics? The effect of rotation should be achieved by tangential scaling. For example, if you rotate the shape by 30 degrees, all else the same:
var deg = Math.PI/180; CTX. Transform (Math. Cos (30 * deg), Math. Sin (30 * deg), - Math. Sin (30 * deg), Math. Cos (30 * deg), 0, 0). The arc (200,50,50,0, Math. PI * 2) . FillRect,50,50 (200100). The stroke ()Copy the code
Among them:
cos(30*deg),
sin(30*deg),
-sin(30*deg),
cos(30*deg)
Copy the code
When you rotate N degrees using transform, N*deg stays the same, just remember the corresponding trig functions cos,sin,-sin,cos. Original blogger imparts memory method :CS-SC= junior three – go to bed, do not forget the minus sign.
Note: Canvas also provides a setTransform method that sets the matrix directly to the value you passed to it, erasing all previous transforms.
A simple application example:
Context. Translate (200);for(var i = 0; i < 80; i++) { context.save(); The context. The transform (0.95, 0,0,0.95, 30, 30); Rotate to (30,30) context.rotate(math.pi /12); // rotate to (30,30) context.rotate(math.pi /12); context.beginPath(); context.fillStyle ="red";
context.globalAlpha="0.4"; Arc (0,0,50,0, math.pi *2, math.pi *2, math.pi *2, math.pi *2, math.pi *2, math.pi *2, math.pi *2true); // context.closePath(); context.fill(); } context. SetTransform (1,0,0,1,10,10); // Empty the transform style and set the new graphic position context.fillstyle ="yellow"; ,0,50,50 context. FillRect (0); context.fill();Copy the code
12. Combination of graphics By default, when two graphics overlap, one will overwrite the other. This can be set through the globalCompositeOperation property.
Too lazy to knock properties show series:
-
The clipping path uses the clip() : Once an area is clipped, all subsequent drawings are restricted to the clipped area (no access to other areas of the canvas). After the clip() is used, only the information before the clip is visible. After the clip, only the graphic part is displayed in the selected area. The rest is hidden. Reference to understand website: https://www.w3cplus.com/canvas/clip.html
-
Use lineWidth, lineGap, lineJoin, and miterLimit to set different line styles. LineWidth: lineWidth (default: 1) lineGap: line endpoint (default: butt) Optional miterLimit: The thickness of the point at which line segments intersect. The larger the lineJoin, the more obvious the style selected
-
To draw a linear gradient, use createLinearGradient() to create a linear gradient object. Then use addColorStop to add different colors to the linear gradient object to achieve the gradient effect.
Example:
// createLinearGradient(start gradient x, start gradient y, end gradient x, end gradient Y)
var shadow = context.createLinearGradient(0.0.200.0); // Can also be understood as the direction of the gradient coordinates
shadow.addColorStop(0.'#ff0000');
shadow.addColorStop(1/7.'#ff9900');
shadow.addColorStop(2/7.'#ffff00');
shadow.addColorStop(3/7.'#00ff00');
shadow.addColorStop(4/7.'#00ffff');
shadow.addColorStop(5/7.'#0000ff');
shadow.addColorStop(6/7.'#ff00ff');
shadow.addColorStop(1."#ff0000");
context.fillStyle =shadow;
context.strokeStyle = shadow;
context.fillRect(10.10.200.200);
Copy the code
Use createRadialGradient() to create a radial gradient object, and then use addColorStop to add different colors to the radial gradient object to achieve the radial gradient effect. Example:
// createRadialGradient(The gradient begins with the circle coordinate x0. It starts with y0, it starts with r0, it ends with x1, it ends with y1, it ends with r1)
var shadow = context.createRadialGradient(85.85.3.100.100.100);
shadow.addColorStop(0."white");
shadow.addColorStop(1."orange");
context.fillStyle= shadow;
context.fillRect(10.10.200.200);
Copy the code
17. Draw patterns
A.c ontext. CreatePattern (image, “repeat | repeat – x | repeat – y | no – repeat”) method for repeated within a specified in the direction of the specified element. Similar to setting the Image background, we create a new Image() object, pass the IMG object into createPattern(img,type), and assign it to fillStyle to fill the Image. Example:
var img = new Image(); . / / to create a new Image object img SRC = "https://www.easyicon.net/api/resizeApi.php?id=1209623&size=128"; Img. onload = function(){var pattern = context.createpattern (img,'repeat'); var pattern = context.createpattern (img,'repeat'); context.fillStyle = pattern; ,0,380,190 context. FillRect (0); }Copy the code
Context. drawImage(img,x,y); Context. DrawImage (img,x,y,width,height); ③ Cut the image and position the cut part on the canvas: Context. DrawImage (img, start clipping position x, start clipping position y, swidth, sheight, x, y, width, height);
var img = new Image(); // Create a new Image object
img.src = "https://www.easyicon.net/api/resizeApi.php?id=1209623&size=128"; // Set the image path
img.onload = function(){ // Load the image
// Create a pattern
context.drawImage(img,0.0);
context.font = "nomal 100px SimHei";
context.shadowOffsetX = 3;
context.shadowOffsetY = 3;
context.shadowBlur = 3;
context.shadowColor = "pink";
context.createPattern(img,'repeat');
context.fillStyle = "white";
context.fillText("wowww".50.165);
}
Copy the code
18. Create shadows
Example:
//设置阴影
context.shadowOffsetX =3; //x轴方向的阴影偏移量,负数为向右偏移量
context.shadowOffsetY =3; //y轴方向的阴影偏移量,负数为向上偏移量
context.shadowBlur = 2;//阴影模糊强度
context.shadowColor = "pink"; // Draw the rectangle context.fillstyle ="orange"; The context. FillRect,20,300,80 (20); // Draw the text context.font ="nomal 45px SimHei"; // Set the text font style context.fillstyle ="white"; // Set the text color, fill the color context.fillText("HTML5/CSS3",30,64)// set the text content and text positionCopy the code
Note: After the shadow is set, both text and rectangle will be shaded.
- Draw fill/outline text
FillText (text content, position X, position Y [, maximum width]). If the length of text content exceeds the maximum width, the text will be compressed automatically
// Draw the fill text context.font ="nomal 45px SimHei"; // Set the text font style context.fillstyle ="white"; // Set the text fill color context.fillText("HTML5/CSS3",30,64)// set the text content and text positionCopy the code
// Draw the outline text context.font ="nomal 45px SimHei"; // Set the text font style context.strokestyle ="white"; // Set the color of the text outline"HTML5/CSS3"; Context.stroketext (text,,30,64)// sets the text content and positionCopy the code
Context. MeasureText (text) Specifies the measureText width.
Small white first time in nuggets to write learning summary, from their own understanding of the point of view of notes, may be understanding of some methods there are mistakes, welcome to point out! Keep learning and updating at….