<canvas></canvas>
is a new tag in HTML5, used to draw graphics. In fact, this tag is the same as other tags. Its special feature is that this tag can obtain a CanvasRenderingContext2D object, which we can use JavaScript scripts to Control this object for drawing.
<canvas></canvas>
is just a container for drawing graphics. In addition to attributes such as id, class, and style, it also has height and width attributes. There are three main steps for drawing on the <canvas>>
element:
<canvas>
element, which is a Canvas object; The following is a simple <canvas>
drawing example:
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <title>canvas drawing demonstration</title> <style type=text/css> #canvas{ border: 1px solid #ADACB0; display: block; margin: 20px auto; } </style></head><body> <canvas id=canvas width=300 height=300> Your browser does not support canvas yet </canvas></body><script type=text/javascript> var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); //Set the object starting point and end point context.moveTo(10,10); context.lineTo(200,200); //Set the style context.lineWidth = 2; context.strokeStyle = #F5270B; //Draw context.stroke();</script></html>
If not specified through moveTo(), the starting point of lineTo() is based on the previous point. Therefore, if you need to reselect the starting point, you need to pass the moveTo() method. If you need to set styles for different line segments, you need to reopen a path through context.beginPath(). Here is an example:
<script type=text/javascript> var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); //Set the starting point and end point of the object context.beginPath(); context.moveTo(100,100); context .lineTo(700,100); context.lineTo(700,400); context.lineWidth = 2; context.strokeStyle = #F5270B; //Draw context.stroke(); context.beginPath(); context.moveTo(100,200); //The effect of replacing moveTo with lineTo here is the same context.lineTo(600,200); context.lineTo(600,400) ; //If the color of strokeStyle has a new value, it will overwrite the value set above. //If lineWidth has no new value, it will be displayed according to the value set above. context.strokeStyle = #0D25F6; //Draw context.stroke();</script >
Draw rectangles rect(), fillRect() and strokeRect()
<script type=text/javascript> var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); //Use the rect method context.rect(10,10,190,190); context.lineWidth = 2; context. fillStyle = #3EE4CB; context.strokeStyle = #F5270B; context.fill(); context.stroke(); //Use fillRect method context.fillStyle = #1424DE; context.fillRect(210,10,190,190); //Use strokeRect method context.strokeStyle = #F5270B; context.strokeRect(410,10,190,190); //Use strokeRect method and fillRect at the same time Method context.fillStyle = #1424DE; context.strokeStyle = #F5270B; context.strokeRect(610,10,190,190); context.fillRect(610,10,190,190);</script>
Two points need to be explained here: The first point is the order before and after stroke() and fill() are drawn. If fill() is drawn later, then when the stroke border is larger, the border drawn by stroke() will be obviously covered. Half; second point: When setting the fillStyle or strokeStyle attribute, you can set it through the setting method of rgba(255,0,0,0.2). The last parameter of this setting is transparency.
There is another one related to rectangular drawing: clearing the rectangular area: context.clearRect(x,y,width,height).
The received parameters are: the starting position of the clear rectangle and the width and length of the rectangle.
In the above code, add at the end of drawing the graph:
context.clearRect(100,60,600,100);
The following effects can be obtained:
Draw a five-pointed starBy analyzing the five-pointed star, we can determine the rules of the coordinates of each vertex. One thing to note here is: in the canvas, the direction of the Y-axis is downward.
The corresponding code is as follows:
var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); context.beginPath(); //Set the coordinates of a vertex and formulate a path based on the vertex for (var i = 0; i < 5; i++ ) { context.lineTo(Math.cos((18+i*72)/180*Math.PI)*200+200, -Math.sin((18+i*72)/180*Math.PI)*200+200); context.lineTo(Math.cos((54+i*72)/180*Math.PI)*80+ 200, -Math.sin((54+i*72)/180*Math.PI)*80+200); } context.closePath(); //Set the border style and fill color context.lineWidth=3; context.fillStyle = #F6F152; context.strokeStyle = #F5270B; context.fill(); context.stroke();
Final effect:
Line propertiesIn addition to the lineWidth attribute used above, lines also have the following attributes:
The lineCap property sets or returns the style of the line cap at the end of the line. It can take the following values:
The lineJoin property sets or returns the type of corner created when two lines meet. It can take the following values:
The miterLimit property sets or returns the maximum miter length (default is 10). Miter length refers to the distance between the inside and outside corners where two lines meet. miterLimit is only valid when the lineJoin attribute is miter.
var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); //Test lineCap property //Set the baseline for easy observation context.moveTo(10,10); context.lineTo(10,200); context. moveTo(200,10); context.lineTo(200,200); context.lineWidth=1; context.stroke(); //butt context.beginPath(); context.moveTo(10,50); context.lineTo(200,50); context.lineCap=butt; context.lineWidth=10; context.stroke(); //round context.beginPath() ; context.moveTo(10,100); context.lineTo(200,100); context.lineCap=round; context.lineWidth=10; context.stroke(); //square context.beginPath(); context.moveTo(10,150); context.lineTo(200,150); context.lineCap=square; context.lineWidth=10; context.stroke(); //Test linJoin property //miter context.beginPath(); context.moveTo(300,50); context.lineTo(450,100); context.lineTo(300,150); context.lineJoin=miter; context.lineWidth=10; context.stroke(); //round context.beginPath(); context.moveTo(400,50); context.lineTo(550,100); context.lineTo(400,150); context.lineJoin=round; context.lineWidth=10; context.stroke(); //square context.beginPath(); context.moveTo(500,50); context.lineTo(650,100); context.lineTo(500,150); context.lineJoin=bevel; context.lineWidth=10; context.stroke(); //Test miterLimit attribute context.beginPath(); context.moveTo(700,50); context.lineTo(850,100); context.lineTo(700,150); context.lineJoin=miter; context.miterLimit=2; context.lineWidth=10; context.strokeStyle=#2913EC; context.stroke();
The effects of different values for each attribute are as follows:
Fill styleIn addition to setting the color, the fillStyle and strokeStyle used previously can also set other fill styles. Here we take fillStyle as an example:
linear gradientUsage steps
(1) var grd = context.createLinearGradient( xstart , ystart, xend , yend ) creates a linear gradient and sets the starting and end coordinates;
(2) grd.addColorStop(stop, color) adds color to the linear gradient, stop is a value of 0~1;
(3) context.fillStyle=grd will be assigned to context.
radial gradientThis method is similar to the linear gradient method, except that the parameters received in the first step are different.
var grd = context.createRadialGradient(x0, y0, r0, x1, y1, r1); receives the coordinates and radius of the starting circle center and the coordinates and radius of the end circle center.
Bitmap paddingcreatePattern( img , repeat-style) is filled with pictures, and repeat-style can be repeat, repeat-x, repeat-y, or no-repeat.
var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); //Linear gradient var grd = context.createLinearGradient(10, 10, 100, 350); grd.addColorStop(0,#1EF9F7); grd.addColorStop(0.25,#FC0F31); grd.addColorStop(0.5,#ECF811); grd.addColorStop(0.75,#2F0AF1); grd.addColorStop(1,#160303); context.fillStyle = grd; context.fillRect(10,10,100,350); //radial gradient var grd = context.createRadialGradient(325, 200, 0, 325, 200, 200); grd.addColorStop(0,#1EF9F7); grd.addColorStop(0.25,#FC0F31); grd.addColorStop(0.5,#ECF811); grd.addColorStop(0.75,#2F0AF1) ; grd.addColorStop(1,#160303); context.fillStyle = grd; context.fillRect(150,10,350,350); //Bitmap filling var bgimg = new Image(); bgimg.src = background.jpg; bgimg.onload= function(){ var pattern = context.createPattern(bgimg, repeat); context.fillStyle = pattern; context.strokeStyle=#F20B0B; context.fillRect(600, 100, 200,200); context.strokeRect(600, 100, 200,200); };
The effect is as follows:
Graphic transformationTranslation: context.translate(x,y), the received parameters are the translation of the origin by x in the x-axis direction and the translation of y in the y-axis direction.
Scaling: context.scale(x,y), the received parameters are that the x coordinate axis is scaled according to the x proportion, and the y coordinate axis is scaled according to the y proportion.
Rotation: context.rotate(angle), the received parameter is the angle of rotation of the coordinate axis.
It should be noted that after changing the graphics, the next drawing will follow the previous state, so if you need to return to the initial state, you need to use context.save();
and context.restore();
Save and restore current state:
var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); //translate() context.save(); context.fillStyle = #1424DE; context.translate(10,10); context.fillRect (0,0,200,200); context.restore(); //scale() context.save(); context.fillStyle = #F5270B; context.scale(0.5,0.5); context.fillRect(500,50,200,200); context.restore(); //rotate() context.save(); context.fillStyle = #18EB0F; context.rotate(Math .PI / 4); context.fillRect(300,10,200,200); context.restore();
The effect is as follows:
Another thing related to graphics transformation is: matrix transformation: context.transform(a, b, c, d, e, f, g). The meaning of the parameters is as follows:
a horizontal scaling (default 1)
b horizontal tilt (default 0)
c vertical tilt (default 0)
d vertical scaling (default 1)
e horizontal displacement (default is 0)
f vertical displacement (default is 0)
Readers can verify the effects of each parameter by themselves, and I will not introduce them one by one here.
draw curveThere are four functions for drawing curves, namely:
context.arc(x,y,r,sAngle,eAngle,counterclockwise); used to create arcs/curves (used to create circles or partial circles). The meaning of the parameters received:
| Parameters | Meaning |
| :--- |:---|
| x | x coordinate of the center of the circle |
|y|Y coordinate of the center of the circle|
|r|radius of circle|
|sAngle|Start angle in radians (the three o'clock position of the arc's circle is 0 degrees)|
|eAngle|End angle in radians|
|counterclockwise|Optional. Specifies whether the plot should be drawn counterclockwise or clockwise. False = clockwise, true = counterclockwise |
Here are a few examples of several arc() functions:
var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); context.strokeStyle = #F22D0D; context.lineWidth = 2; //Draw a circle context.beginPath(); context.arc(100,100,40 ,0,2*Math.PI); context.stroke(); //Draw a semicircle context.beginPath(); context.arc(200,100,40,0,Math.PI); context.stroke(); //Draw a semicircle, counterclockwise context.beginPath(); context.arc(300,100,40,0,Math.PI,true) ; context.stroke(); //Draw a closed semicircle context.beginPath(); context.arc(400,100,40,0,Math.PI); context.closePath(); context.stroke();
The effect is as follows:
context.arcTo(x1,y1,x2,y2,r); Creates an arc/curve on the canvas between two tangents. The meaning of the parameters received:
parameter | meaning |
---|---|
x1 | x-coordinate of the arc’s control point |
y1 | The y coordinate of the arc's control point |
x2 | x-coordinate of the arc's end point |
y2 | The y coordinate of the arc's end point |
r | radius of arc |
What needs to be noted here is that the starting point of the curve drawn by the arcTo function needs to be set through the moveTo() function. The arcTo function is used below to draw a rounded rectangle:
function createRoundRect(context, x1, y1, width, height, radius) { // Move to the upper left corner context.moveTo(x1 + radius, y1); // Add a line segment connected to the upper right corner context.lineTo(x1 + width - radius, y1); //Add an arc context.arcTo(x1 + width, y1, x1 + width, y1 + radius, radius); // Add a line segment connected to the lower right corner context.lineTo(x1 + width, y1 + height - radius); // Add an arc context.arcTo(x1 + width, y1 + height, x1 + width - radius, y1 + height , radius); // Add a line segment connected to the lower left corner context.lineTo(x1 + radius, y1 + height); // Add an arc context.arcTo(x1, y1 + height, x1, y1 + height - radius, radius); // Add a line segment connected to the upper left corner context.lineTo(x1, y1 + radius); // Add an arc Arc context.arcTo(x1, y1, x1 + radius, y1, radius); context.closePath(); } // Get the DOM object corresponding to the canvas element var canvas = document.getElementById('mc'); // Get the CanvasRenderingContext2D object drawn on canvas var context = canvas.getContext('2d'); context.lineWidth = 3; context.strokeStyle = #F9230B; createRoundRect(context, 30, 30, 400, 200, 50); context.stroke();
The effect is as follows:
context.quadraticCurveTo(cpx,cpy,x,y); Draw a quadratic Bezier curve. The parameter meanings are as follows:
parameter | meaning |
---|---|
cpx | The x coordinate of the Bezier control point |
cpy | The y coordinate of the Bezier control point |
x | x coordinate of end point |
y | y coordinate of the end point |
The starting point of the curve is the last point in the current path. If the path does not exist, use the beginPath() and moveTo() methods to define the starting point.
context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y); Draw a cubic Bezier curve with the following parameters:
parameter | meaning |
---|---|
cp1x | x coordinate of the first Bezier control point |
cp1y | The y coordinate of the first Bezier control point |
cp2x | x coordinate of the second Bezier control point |
cp2y | The y coordinate of the second Bezier control point |
x | x coordinate of end point |
y | y coordinate of the end point |
There are mainly three properties and three methods related to text rendering:
property | describe |
---|---|
font | Sets or returns the current font properties of text content |
textAlign | Sets or returns the current alignment of text content |
textBaseline | Sets or returns the current text baseline used when drawing text |
method | describe |
---|---|
fillText() | Draw filled text on canvas |
strokeText() | Draw text on canvas (no padding) |
measureText() | Returns an object containing the specified text width |
The basic usage of the above properties and methods is as follows:
var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); context.font=bold 30px Arial; //Set the style context.strokeStyle = #1712F4; context.strokeText(Welcome to my blog! ,30,100); context.font=bold 50px Arial; var grd = context.createLinearGradient( 30 , 200, 400, 300 );//Set the gradient fill style grd.addColorStop(0,#1EF9F7); grd.addColorStop(0.25,#FC0F31); grd.addColorStop(0.5,#ECF811); grd.addColorStop(0.75, #2F0AF1); grd.addColorStop(1,#160303); context.fillStyle = grd; context.fillText(Welcome to my blog!,30,200); context.save(); context.moveTo(200,280); context.lineTo(200,420) ; context.stroke(); context.font=bold 20px Arial; context.fillStyle = #F80707; context.textAlign=left; context.fillText(The text starts at the specified position, 200,300); context.textAlign=center; context.fillText(The center of the text is placed at the specified position, 200,350); context.textAlign= right; context.fillText(text ends at the specified position, 200, 400); context.restore(); context.save(); context.moveTo(10,500); context.lineTo(500,500); context.stroke(); context.fillStyle=#F60D0D; context.font=bold 20px Arial; context.textBaseline=top; context.fillText(specified position is above, 10,500); context.textBaseline=bottom; context.fillText (specified position is below, 150,500); context.textBaseline=middle; context.fillText (specified position is in the middle, 300,500); context.restore(); context.font=bold 40px Arial; context.strokeStyle = #16F643; var text = Welcome to my blog! ; context.strokeText(Welcome to my blog!,10,600); context.strokeText(The width of the above string is: +context.measureText(text).width,10,650);
The effect is as follows:
Other properties and methods Shadow drawing:Let's add a shadow to the five-pointed star we drew earlier
var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); context.beginPath(); //Set the coordinates of a vertex and formulate a path based on the vertex for (var i = 0; i < 5; i++ ) { context.lineTo(Math.cos((18+i*72)/180*Math.PI)*200+200, -Math.sin((18+i*72)/180*Math.PI)*200+200); context.lineTo(Math.cos((54+i*72)/180*Math.PI)*80+ 200, -Math.sin((54+i*72)/180*Math.PI)*80+200); } context.closePath(); //Set the border style and fill color context.lineWidth=3; context.fillStyle = #F6F152; context.strokeStyle = #F5270B; context.shadowColor = #F7F2B4; context.shadowOffsetX = 30; context.shadowOffsetY = 30; context.shadowBlur = 2; context.fill(); context.stroke();
The effect is as follows:
Graphic combination:globalAlpha: Sets or returns the current alpha or transparency value of the drawing
This method is mainly to set the transparency of graphics, which will not be introduced in detail here.
globalCompositeOperation: Sets or returns how the new image is drawn onto the existing image. This method has the following attribute values:
value | describe |
---|---|
source-over | Display source image over target image (default) |
source-atop | Displays the source image on top of the destination image. The parts of the source image that lie outside the target image are invisible |
source-in | Display the source image within the target image. Only the portion of the source image within the destination image will be displayed; the destination image is transparent |
source-out | Displays the source image in addition to the target image. Only the portion of the source image outside the destination image is displayed, and the destination image is transparent |
destination-over | Display target image over source image |
destination-atop | Displays the destination image on top of the source image. The parts of the target image that lie outside the source image are invisible |
destination-in | Displays the destination image within the source image. Only the portion of the target image within the source image will be displayed, and the source image is transparent |
destination-out | Displays the target image in addition to the source image. Only the portion of the target image outside the source image will be displayed, and the source image is transparent |
lighter | Display source image + target image |
copy | Show source image. Ignore target image |
xor | Combine source and destination images using XOR operation |
Here's a small example of how the combination can be changed with a click:
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <title>Graphic combination</title> <style type=text/css> #canvas{ border: 1px solid #1C0EFA; display : block; margin: 20px auto; } #buttons{ width: 1000px; margin: 5px auto; clear:both; } #buttons a{ font-size: 18px; display: block; float: left; margin-left: 20px; } </style></head><body> <canvas id=canvas width=1000 height=800> Your browser is not yet Support canvas </canvas> <div id=buttons> <a href=#>source-over</a> <a href=#>source-atop</a> <a href=#>source-in</a> <a href=#>source-out</a> <a href=#>destination-over</a> <a href=#>destination-atop</a> <a href=#>destination-in</a> <a href=#>destination-out</a> <a href=#>lighter</a> <a href=#>copy</a> <a href=#>xor</a> </div></body><script type=text/javascript>window.onload = function(){ draw(source-over); var buttons = document.getElementById(buttons). getElementsByTagName(a); for (var i = 0; i < buttons.length; i++) { buttons[i].onclick = function(){ draw(this.text); return false; }; }}; function draw(compositeStyle){ var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); context.clearRect(0, 0, canvas.width, canvas.height); //draw title context.font = bold 40px Arial; context.textAlign = center; context.textBasedline = middle; context.fillStyle = #150E0E; context.fillText(globalCompositeOperation = +compositeStyle, canvas.width/2, 60); //draw a rect context.fillStyle = #F6082A; context.fillRect(300, 150, 500, 500); //draw a triangle context. globalCompositeOperation = compositeStyle; context.fillStyle = #1611F5; context.beginPath(); context.moveTo(700, 250); context.lineTo(1000,750); context.lineTo(400, 750); context.closePath(); context.fill(); }</script> </html>
Readers can click on the label to observe different combination effects. The effects are as follows:
Clipping area:The clip() method cuts any shape and size from the original canvas.
Tip: Once you clip an area, all subsequent drawing is restricted to the clipped area (no other areas on the canvas can be accessed). You can also save the current canvas area by using the save() method before using the clip() method, and restore it at any time in the future (via the restore() method)
The following is an example of using a circle to intercept a rectangle:
var canvas = document.getElementById(canvas); var context = canvas.getContext(2d); context.beginPath(); context.fillStyle = #0C0101; context.fillRect(0,0,canvas.width,canvas.height); context.beginPath(); context.fillStyle = #FFFDFD; context.arc(400,400,100,0,2*Math.PI); context.fill(); context.clip(); context.beginPath(); context.fillStyle = #F60825; context.fillRect(200, 350, 400, 50);
In addition to the above attributes and methods, there are also the following methods:
drawImage(): Draws an image, canvas or video to the canvas.
toDataURL(): save graphics
isPointInPath(): Returns true if the specified point is in the current path, false otherwise.
I won’t give examples one by one here.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.