Table of Contents
1.Canvas element
1.Canvas element definition
2. Use JavaScript to obtain the Canvas object in the page
2. Draw graphics
1. Draw a straight line
2. Draw a rectangle
(1)rect()
(2)strokeRect()
(3) fillRect() and clearRect() functions
3. Draw an arc
4. Stroke and fill
5.Gradient color
6.Transparent color
3. Draw images and text
1. Draw an image
2. Combination chart
3. Output text
4. Graphic operations
一.Canvas element
Canvas means canvas. This is a new element in HTML5. You can define a canvas on the page to implement drawing functions.
1.Canvas element definition
grammar:
<canvas id="xxx" height= width= >When the browser does not support Canvas, the text here is displayed</canvas>
id Identification of the canvas element
height canvas height
width Canvas width
For example, define a canvas:
<canvas id="canvas" width="600" height="960">Browser not supported</canvas>
2. Use JavaScript to get the Canvas object in the page
In JavaScript, you can use the document.getElementById() method to obtain the object in the web page. After obtaining the object, obtain the 2D context object of the object through the getContext() function, and then you can draw on the canvas.
grammar:
docment.getElementById(ObjectId)
example:
<canvas id="canvas" width="600" height="960">Browser not supported</canvas>
2. Draw graphics
1. Draw a straight line
beginPath() starts the drawing function
moveTo() This function moves the coordinates to the specified coordinates. The function parameters are x, y
lineTo() draws a straight line
stroke() draws the boundary outline of the graphic
For example, draw a triangle:
Title <canvas id="canvas" width="600" height="960">Browser not supported</canvas>
Effect:
Another example of drawing complex patterns:
Title <canvas id="canvas" width="600" height="960">Browser not supported</canvas>
Effect:
2. Draw a rectangle
You can draw a rectangle through the rect() function and strokeRect() function, call fillRect() to fill the area of the specified rectangle, and call clearRect() to erase the rectangle of the specified area.
(1)rect()
This function is used to draw a rectangle, syntax:
Rect(x,y,width,height)
x,y represents the starting point of the rectangle
width, height represents the length and width of the rectangle
(2)strokeRect()
This function is similar to the rect() function, both draw rectangles, but this function does not need to call beginPath() and closePath() like rect() when drawing. Syntax:
storkeRect(x,y,width,height)
(3) fillRect() and clearRect() functions
fillRect() draws a filled rectangle, syntax:
fillRect(x,y,width,height)
clearRect() clears the rectangle, syntax:
clearRect(x,y,width,height)
For example:
Title <canvas id="canvas" width="600" height="960">Browser not supported</canvas>
Effect:
3. Draw an arc
Draw arc function arc(), syntax:
arc(centerX,centerY,radius,startingAngle,endingAngle,antiClockwise);
parameter:
centerX X coordinate of arc center
centerY Y coordinate of arc center
radius The radius of the arc
startingAngle The starting angle of the arc
endingAngela The ending angle of the arc
antiClockwise Whether to draw counterclockwise
For example:
Title <canvas id="canvas" width="600" height="960">Browser not supported</canvas>
Effect:
4. Stroke and fill
The strokeStyle property of the Canvas 2D context object can set the stroke color, the lineWidth property can specify the stroke width, and the fillStyle property can set the fill color.
For example, draw a red-edged circle and a yellow rectangle:
Title <canvas id="canvas" width="600" height="960">Browser not supported</canvas>
Effect:
5.Gradient color
CanvasGradient is used to define a gradient color object in the canvas. The object must be created before using the gradient color. The gradient color object can be created in two ways:
(1) Create a CanvasGradient object with a linear color gradient, function createLinearGradient() syntax:
createLinearGradient(xStrat,yStrat,xEnd,yEnd)
The parameters are the linear start coordinate and end coordinate respectively.
(2) Create a CanvasGradient object with a radial color gradient, function createRadiaGradient() syntax:
createRadiaGradient(xStart,yStart,radiusStart,xEnd,yEnd,radiusEnd)
parameter:
xStart, yStart Center coordinates of the starting circle
radiusStart The radius of the starting circle
xEnd, yEnd Center coordinates of the ending circle
radiusEnd The radius of the ending circle
(3) Set color for gradient object
After creating a gradient color object, you can add a color change at a certain point of the gradient through the addColorStop() method of the CanvasGradient property. Syntax:
addColorStop(offset,color)
offset A floating point value in the range 0 to 1 that represents part of the beginning and end of the gradient
color means offset to color
(4) Set the stroke style to gradient color
As long as you assign the previously created CanvasGradient object to the context 2d object of Canvas, you can use the gradient color to stroke.
For example:
Title <canvas id="canvas" width="600" height="960">Browser not supported</canvas>
Effect:
6. Transparent color
When specifying a color, you can use the rgba() method to define color transparency. Syntax:
rgba(r,g,b,alpha)
Parameters: r represents the red set, b represents the green set, and b represents the blue set. They are all decimal numbers, ranging from 0 to 255.
alpha represents transparency, the value range is 0~1
For example:
Title <canvas id="canvas" width="600" height="960">Browser not supported</canvas>
Effect:
3. Drawing images and text
1. Draw an image
The method for drawing images on Canvas canvas is drawImage(), syntax:
drawImage(image,x,y) drawImage(image,x,y,width,height) drawImage(image,sourceX,sourceY,sourceWidth,sourceHeight,destX,destY,destWidth,destHeight)
image the image to draw
x,y to draw the upper left corner of the image
width, height draw the width and height of the image
sourceX, sourceY The upper left corner of the area where the image will be drawn
sourceWidth, sourceHeight The original image area being drawn
destX, destY Canvas coordinates of the upper left corner of the image area to be drawn
destWidth, destHeight The size of the image area to be drawn on the canvas
For example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> </style> </head> <body> <canvas id="canvas" width="2000" height="1000">Browser not supported</canvas> <script> function f() { var c=document.getElementById("canvas"); //Get the canvas object var ctx=c.getContext("2d"); //Get the 2d context object var ImageObj=new Image(); ImageObj.src="mn1.png"; ImageObj.onload=function () { ctx.drawImage(ImageObj,0,0) //Original image size ctx.drawImage(ImageObj,980,0,480,300) //Half of the original image is displayed //Cut an image size of 300x300 from the original image (500, 0), display it at (980,350), and the display size is 300x300 ctx.drawImage(ImageObj,500,0,300,300,980,350,300,300); }; } window.addEventListener("load",f,true); </script> </body> </html>
Effect:
2. Combination chart
If there is already a graphic on the canvas and we put another one, we have to consider the combination of the pictures. The globalCompositeOperation property of the 2d context object of Canvas can set the combination method. The property parameters are as follows:
Parameter | Description |
source-over | Default value, new The image will be overlaid on the original image |
destination-over | Display the image under the original content |
source-in | Only the parts of the new image that overlap with the original content appear, and other areas become transparent |
destination-in |
The non-duplicate parts of the original content and new images will be retained. |
source-atop | The parts of the new image that overlap with the original content will be drawn and overlay the original content |
destination-atop | The duplicate parts of the original content and the new image will be retained, and graphics will be drawn under the original content |
source-in | Only the non-duplicate parts of the new image and the original content will be drawn |
destination-in | The non-overlapping parts of the original content and the new image will be retained |
lighter | The overlapping parts of the two images will be colored |
darker | The repeated parts in the two images are subtracted |
xor | The repeated part will become transparent |
copy | Only the new image will be retained, and the others will be cleared |
For example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <canvas id="canvas" width="2000" height="1000">Browser not supported</canvas> <script> function draw(){ var c=document.getElementById("canvas"); var ctx=c.getContext("2d"); ctx.fillStyle="blue"; ctx.fillRect(0,0,100,100); ctx.fillStyle="red"; ctx.globalCompositeOperation="source-over"; var centerX=100; var centerY=100; var radius=50; var startingAngle=0; var endingAngle=2*Math.PI; ctx.beginPath(); ctx.arc(centerX,centerY,radius,startingAngle,endingAngle,false); ctx.fill(); } window.addEventListener("load",draw,true); </script> </body> </html>
Effect:
source-over
destination-over
source-in
destination-in
source-out
destination-out
source-atop
source-atop
lighter
xor
copy
3. Output text
(1) Output
Use the strokeText() method to output text on the specified text of the canvas. Syntax:
stroketText(string text,float x,float y)
Parameters: text text x, y text output position
For example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <canvas id="canvas" width="2000" height="1000">Browser not supported</canvas> <script> function draw(){ var c=document.getElementById("canvas"); var ctx=c.getContext("2d"); ctx.strokeText("hello world-----hello time",200,200); } window.addEventListener("load",draw,true); </script> </body> </html>
Effect:
(2) Set font
Set the string font through the Context.font property, format:
Context.font="Font size font name"
example:
var c=document.getElementById("canvas"); var ctx=c.getContext("2d"); ctx.font="10pt bold"; ctx.strokeText("Hello world! Hello good time!",200,200);
(3) Set border width and color
stokeStyle sets the color of text
(4) Fill inside the text
The text output using the strokeText method is hollow, and only the border is drawn. If you want to fill the inside of the text, you can use the fillText() method. The syntax is:
fillText(string text,float x,float y)
You can also use the fillstyle attribute to set the fill color
ctx.fiilStyle="blue";
For example gradient fill color:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <canvas id="canvas" width="2000" height="1000">Browser not supported</canvas> <script> function draw(){ var c=document.getElementById("canvas"); var ctx=c.getContext("2d"); var Colordiagonal=ctx.createLinearGradient(100,100,900,100); Colordiagonal.addColorStop(0,"yellow"); Colordiagonal.addColorStop(0.5,"green"); Colordiagonal.addColorStop(1,"red"); ctx.fillStyle=Colordiagonal; ctx.font="60pt official script"; ctx.fillText("Hello world! Hello good time!",100,100); } window.addEventListener("load",draw,true); </script> </body> </html>
Effect:
4. Graphic operation
(1) Maintain and restore drawing status
Calling the Context.save() method can maintain the current drawing state. The drawing state is saved in a heap. Calling the Context.restoe() method pops up the previously saved drawing state. These two methods have no parameters.
For example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <canvas id="canvas" width="2000" height="1000">Browser not supported</canvas> <script> function draw(){ var c=document.getElementById("canvas"); var ctx=c.getContext("2d"); ctx.fillStyle='red'; ctx.fillRect(0,0,150,150); //red rectangle ctx.save(); //Save drawing state ctx.fillStyle="blue"; ctx.fillRect(0,200,150,150); //Blue rectangle ctx.restore(); //Restore the previously saved drawing state, which is red ctx.fillRect(200,200,150,150) } window.addEventListener("load",draw,true); </script> </body> </html>
Effect:
(2) Graphic transformation
a. Translate translate(x,y)
The parameters x and y represent the respective translational displacements from the origin.
b.Scale scale(x,y)
The parameters x and y represent the coordinate axis scaling ratio
c. Rotate rotate(angle)
The parameter angle is the angle of rotation of the coordinate axis
d. Transform setTransform()
Syntax:
setTransform(m1,m2,m3,m4,dx,dy)
Indicates the transformation of point (x, y) to point (X, Y). The transformation process:
X=m1*x + m3*y + dx, Y=m2*x + m4*y + dy
For example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <canvas id="canvas" width="2000" height="1000">Browser not supported</canvas> <script> function draw(){ var c=document.getElementById("canvas"); var context=c.getContext("2d"); context.save(); context.fillStyle="#EEEEFF"; context.fillRect(0,0,400,300); context.fillStyle="rgba(255,0,0,0.1)"; context.fillRect(0,0,100,100); context.translate(100,100); context.scale(0.5,0.5); context.rotate(Math.PI/4); context.fillRect(0,0,100,100); context.restore(); context.beginPath(); context.arc(200,50,50,0,2*Math.PI,false); context.stroke(); context.fill(); } window.addEventListener("load",draw,true); </script> </body> </html>
Effect: