Canvas What is it?
Canvas English canvas , yes HTML5 An element that can draw a series of images on it .
Canvas Usage scenarios of
Can be used for animation 、 Game screen 、 Data visualization 、 Image editing and real-time video processing .
Basic usage
stay HTML In file
<canvas id="canvasBox" width="" height=""></canvas>
<!--
annotation :
canvas Must be a closed label </canvas> Don't save , If you omit the rest of the document, it will not display
There are only two properties width and height If the width and height are not set, the default width is 300 high 150
-->stay JS In file
const canvasBox=document.querySelector("#canvasbox");// Get canvas elements
const ctx=canvasBox.getContext(contextType);
/* Get rendering context ( Have the ability to draw and process display content )
contextType Parameters have
2d: draw 2d Images ( Create a CanvasRenderingContext2D Object as 2d Render context )
webgl(experimental-webgl)、webgl2: draw 3d Images ( experimental )
bitmaprenderer: Draw the bitmap on canvas In context ( experimental )
*/canvas The way in which figures are drawn :
First through the rectangle
For example, draw a rectangle :
fillRect(x,y,width,height)// Coordinates of the starting point of the rectangle (x,y) The width and height of the rectangle (width,height)
ctx.fillRect(0,0,300,150)// Draw a starting point coordinate of (0,0) The width and height are respectively 300px,150px The rectangular
strokeRect(x,y,width,height)// Draw a rectangular border (x,y) Start coordinate rectangle length and width (width,height)
ctx.strokeRect(0,0,300,150)// Draw a starting point coordinate of (0,0) The length and width are respectively 300,150
clearRect(x,y,width,heihgt)// Clear the specified rectangular area , Make the clear part completely transparent .
ctx.clearRect(x,y,width,heihgt) // Clear a rectangular border (x,y) Start coordinate clear rectangle length and width (width,height) Second pass path
Draw a straight line
ctx.beginPath();// Start drawing a new path
ctx.moveTo(x,y)// Path start coordinates
ctx.lineTo(x,y);// Draw a line to the specified coordinate point
...
ctx.closePath()// Closed path
ctx.stroke();// Actual drawing path draw a curve
ctx.moveTo(x, y);// The starting point
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);// They are the horizontal and vertical coordinates of the first control point, the horizontal and vertical coordinates of the second control point and the horizontal and vertical coordinates of the end point
ctx.stroke();// Actual drawing path Draw the quadratic Bessel curve
ctx.moveTo(x, y);// The starting point
ctx.quadraticCurveTo(cpx, cpy, x, y);// They are the horizontal and vertical coordinates of the first control point and the horizontal and vertical coordinates of the end point
ctx.stroke();// Actual drawing path Draw the arc
context.beginPath();// Start drawing a new path
ctx.arc(x, y, radius, startAngle, endAngle [, anticlockwise])// Arc center horizontal and vertical coordinate radius angle of arc start angle of arc end angle
context.stroke();// Actual drawing path Draw a rectangle
ctx.rect(x,y,width,height)// The horizontal and vertical coordinates, width and height of the starting point of the rectangle
context.stroke();// Actual drawing path Ellipse drawing
ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
// The horizontal and vertical coordinates of the circle center corresponding to the elliptical arc the radius of the long and short axes of the elliptical arc the rotation angle of the elliptical arc the starting and ending angles of the arc are clockwise and counterclockwise
context.stroke()// Actual drawing path About style related settings
Line style settings
ctx.lineWidth=number// Set the width of the line
ctx.lineCap=// The styles of thread ends are respectively buzz( Default ),round( arc ) and square( Fangtou )
ctx.lineJoin=//miter: Sharp corners round: Round corners bevel: Flat angle
ctx.miterLimit = value;//0-10// Set the sharp corner length and lineJoin The property value is miter In combination with
ctx.getLineDash()// Get an even array of dashed values of the current line
ctx.setLineDash()// The line is a dashed line. The parameter is an array if it is [] Solid line
context.lineDashOffset=value// The offset distance drawn by the dotted line defaults to 0 Is a floating point number Fill stroke
ctx.fillStyle=// Fill color color gradient pattern
ctx.strokeStyle=// Border color color gradient pattern
ctx.stroke()// Draw the path Images and pixels ( a key )
// usage :
/* Parameter description
image: Image resources
Plan an area on the canvas
dx: Abscissa of the planning area
dy: The vertical coordinate of the planning area
dWidth: The width of the planning area
dHeight: The height of the planning area
Picture elements are drawn in Canvas canvas
sx: Starting abscissa
sy: Starting ordinate
sWidth: Picture elements are calculated from the coordinate point , How wide is the content
sHeight: Picture elements are calculated from the coordinate point , How high the content is */
context.drawImage(image, dx, dy);
context.drawImage(image, dx, dy, dWidth, dHeight);
context.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
// Example
let image= new Image(); // Create an empty element
image.src = Url; // route
image.onload = function(){
// ctx.drawImage(image,0,0)
ctx.drawImage(image,41,74,64,82,0,0,128,164) // The parameters in turn are the picture to be drawn , The picture is drawn from that coordinate point , The size of the drawn area will draw the picture , The position of the drawing in the canvas and the size of the drawing in the canvas
} Text
/*
Parameter description :
text Text content
x,y The starting coordinate position of the text in the canvas
maxWidth The maximum width occupied by the text ( Force compression without line breaks )
*/
ctx.fillText(text, x, y [, maxWidth]);// Draw text
ctx.strokeText(text, x, y [, maxWidth]);// Draw a text border
ctx.measureText(text)// obtain TextMetrics Object measures the width of the text
// About the style of text
ctx.font=""// Set text font size
/*
vulue text alignment
left: Align left
right: Right alignment
center: Align center
start: Start azimuth alignment
end: End azimuth alignment
*/
ctx.textAlign=valuestate
ctx.save()// Storage
context.restore();// Pop up storage status The gradient
/*
Linear gradient
x0,y0 Horizontal and vertical coordinates of gradient starting point
x1,y1 Horizontal and vertical coordinates of gradient end point
*/
ctx.createLinearGradient(x0, y0, x1, y1);
/*
Mirror gradient
x0,y0 The coordinates of the center of the starting circle
r0 The radius of the starting circle
x1,y1 The coordinates of the center of the end circle
r1 End circle radius
*/
ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);deformation
ctx.rotate(angle)// The unit of rotation is radians
ctx.scale(x,y)// The zoom
ctx.translate(x,y)// Displacement
ctx.transform(a,b,c,d,e,f)// Deformation: horizontal scaling, horizontal oblique cutting, vertical oblique cutting, vertical scaling, horizontal displacement, vertical displacement
ctx.setTransform()// The same as above will completely reset the existing transformation shadow
ctx.shadowBlur = value;// Shadow size
ctx.shadowColor = color;// Shadow color
ctx.shadowOffsetX = offset;// Shadow horizontal offset
ctx.shadowOffsetY = offset;// Shadow vertical offset Transparency and hierarchy
ctx.globalAlpha = value;// transparency 0-1
/*
type Parameter description :
source-over: Directly overlay the original layer and overlay each other ( Pure visual coverage )
source-in: Show only areas that overlap each other ( The new content is the display layer , The original content is the mask layer )
source-out: and source-in contrary ( The overlapping position is transparent )
source-atop: The overlapped content is masked like the normal display without overlap
****destination-* and source-* The display body is relative to destination Take the original layer as the display host sourc Display hosted by the new layer ****
destination-over
destination-in
destination-out
destination-atop
lighter: Mixed mode
copy: Show only new content
xor: Overlapping areas are transparent
multiply: Positive iteration
screen: Filter color
overlay: superposition
darken: Darken
lighten: Brighten
color-dodge: Color fades
color-burn: The color deepened
hard-light: A strong light
soft-light: Soft light
difference: differences
exclusion: exclude
hue: tonal
saturation: saturation
color: Color value
luminosity: brightness */
ctx.globalCompositeOperation = type;Pattern related
/*
imag: Tiled CanvasImageSource Images
repetition:
repeat Tile horizontally and vertically
no-repeat Don't spread
repeat-x Tile horizontally
repeat-y Tile vertically
*/
ctx.createPattern(image, repetition);Position detection
/*
Parameter description
x,y The horizontal and vertical coordinates of the detected point
fillRule Parameter filling rule
nonzero: Nonzero rule , This is the default rule .
evenodd: Parity rule .
*/
// Check whether the point is within the specified path
ctx.isPointInPath(x, y);// Return value true and false
ctx.isPointInPath(x, y, fillRule);// Return value true and false
/*
x,y The horizontal and vertical coordinates of the detected point
path finger Path2D object */
// Check whether the point is on the path
context.isPointInStroke(x, y);// Return value true and fasle
context.isPointInStroke(path, x, y);// ditto That's all canvas frequently-used api, For more detailed study, please see CanvasAPI The related documents









