1. Use requestAnimationFrame
- The browser optimally determines the redraw sequence.
1. Early timed animation
- Time accuracy cannot be guaranteed.
2. Time interval problem
3, requestAnimationFrame
-
Receives an argument that is the function to be called before the screen is redrawn. To implement looping animations, multiple RequestAnimationFrames () can be strung together.
function updateProgress() { let div = document.getElementById('status') div.style.width = (parseInt(div.style.width, 10) +5) +The '%' if(div.style.left ! ='100%'){ requestAnimationFrame(updateProgress) } } requestAnimationFrame(updateProgress) Copy the code
- It’s only going to be called once so it’s going to loop around and control when it ends.
- The function passed in can take one argument, which is an instance of DOMHighResTimeStamp
- Such as
performance.now()
The return value of. Represents the time of the next redraw.
- Such as
4, cancelAnimationFrame
- Return a request ID, one for passing another
cancelAnimationFrame()
Method to cancel the redraw task.
let requestID = window.requestAnimationFrame(() = >{
console.log('Repaint! ')})window.cancelAnimationFrame(requestID)
Copy the code
5. Throttle through requestAnimationFrame
-
Recursively adding callback functions to the queue ensures that callback functions are called at most once per redraw
let enabled = true function expensiveOperation() { console.log("Invoked at".Date.now()) } window.addEventListener('scroll'.() = > { if(enabled) { enabled = false window.requestAnimationFrame(expensiveOperation) window.setTimeout(() = > enabled = true.50)}})Copy the code
2. Basic canvas function
-
Width and height properties to set the canvas size.
-
GetContext () : Gets a reference to the drawing context, passing the “2D” argument to the flat figure.
-
ToDataURL () : Exports the image on < Canvas >
- Parameter: MIME type
let drawing = document.getElementById("drawing") if(drawing.getContext){ let imgURI = drawing.toDataURL("image/png") let image = document.createElement("img") img.src = imgURI document.body.appendChild(image) } Copy the code
-
This method throws an error if the image in the canvas is drawn from another domain.
3. 2D drawing context
Fill and Stroke
- Fill automatically fills the shape with a specified style (color, gradient, or image), and stroke colors only the borders.
fillStyle
: fillstrokeStyle
: stroke- The property can be a string, a gradient object, or a pattern object
- The default “# 000000”
- The string indicates that the color can be any CSS format
let drawing = document.getElementById("drawing")
if(drawing.getContext){
let context = drawing.getContext("2d")
context.strokeStyle = "red"
context.fillStyle = "#0000ff"
}
Copy the code
- All subsequent stroke and fill operations will use these styles, triggering further modifications.
2. Draw a rectangle
-
FillRect () : Used to draw and fill a rectangle on the canvas with the specified color
-
StrokeRect () : Used to draw a rectangular outline on the canvas with the specified color
- Stroke width:
lineWidth
The integer - Endpoint state:
lineCap
(Butt flat head, round head, square head) - Line intersection shape:
lineJoin
(Round, bevel flat, miter pointed)
- Stroke width:
-
ClearRect () : Erases an area of the canvas
- Parameters: rectangle x coordinate, rectangle y coordinate, rectangle width, rectangle height
3. Draw a path
- To draw a path, call
befinPath()
Indicates to begin drawing a path arc(x, y, radius, startAngle, endAngle, counterclockwise)
- Draw an arc with coordinates (x, y) as the center and radius as the radius. The startAngle is startAngle and the endAngle is endAngle. Counterclockwise shows whether the starting and ending angles are calculated counterclockwise (clockwise by default)
arcTo(x1, y1, x2, y2, radius)
- For a given radius, draw an arc from the previous point to (x2, y2) through (x1, y1)
bezierCurveTo(c1x, c1y, c2x, c2y, x, y)
- Plot an arc from the top point to (x,y) using (c1x, c1y),(c2x, c2y) as control points (cubic Bezier curve)
lineTo(x, y)
- Draw a line from the top point to (x, y)
moveTo(x, y)
- Instead of drawing a line, just move the draw cursor to (x, y)
quadraticCurveTo(cx, cy, x, y)
- Plot an arc (quadratic Bessel curve) from the top point to (x, y) with (cx, cy) as the control point
rect(x, y, width, height)
- Draws a rectangle at the coordinate points (x, y) with the given width and height.
- It differs from strokeRect and fillRect in that it creates a path rather than a separate graph
- Create a path and pass
closePath()
Method draws a line that returns to the starting point. If the path is complete, yes- The specified
fillStyle
Property and callfill()
Method to populate the path - The specified
strokeStyle
Property and callstroke()
Method to trace the path - call
clip()
Method to create a new clipping region based on an existing path
- The specified
isPointInPath(x, y)
- Is the point (x, y) on the path
4. Draw text
fillText()
和strokeText()
- Parameters: string to draw, x coordinate, y coordinate, optional maximum pixel width
- Based on the attribute
font
CSS syntax specifies the font style, size, font family, and so ontextAlign
: Specifies how the text works- Start, end, left, right, center
textBaseLine
: Baseline of the text- Top, hanging, middle, Alphabetic, ideographic, and bottom
measureText()
Used to aid in sizing text, receives one parameter, the text to draw, and returns oneTextMetrics
Object containing the width property.- Calculates the size after drawing the specified text using the property
- Fourth parameter: Maximum pixel width If the maximum width limit is exceeded, the character is compressed horizontally.
5, transform
-
Will change the matrix with the default initial value.
-
Rotate (Angle) : Rotates the image Angle around the origin
-
Scale (scaleX, scaleY) : Scale the image by multiplying scaleX on the x axis and scaleY on the y axis, default 1.0
-
Translate (x, y) : Change the origin to (x, y). The coordinate 0, 0 will become the coordinate x, y.
-
Transform (M1_1, M1_2, M2_1, M2_2, dx, dy) : Modify matrix by matrix multiplication
m1_1 m1_2 dx m2_1 m2_2 dy 0 0 1 Copy the code
-
SetTransform (m1_1, M1_2, m2_1, m2_2, dx, dy) : Reset the matrix to the default value and call transform with the parameters passed in
-
All transformations, including the fillStyle and strokeStyle attributes, remain in context until they are modified again. The current state is saved using the save() method and the previously saved Settings are returned using the restore() method
-
Only Settings and transformations applied to the drawing context are saved, not the contents of the drawing context.
6. Draw images
drawImage()
- Three parameters: Position the image on the canvas
- Img, one
<img>
Elements, or<canvas>
The element - X, represents the x coordinate of the drawing target
- Y, the y coordinate of the target to draw
- Img, one
context.drawImage(img,x,y);
Copy the code
- Five parameters: position the image on the canvas and specify the width and height of the image
- Img, one
<img>
Elements, or<canvas>
The element - X, represents the x coordinate of the drawing target
- Y, the y coordinate of the target to draw
- Width, the target width
- Height, target height
- Img, one
context.drawImage(img,x,y,width,height);
Copy the code
- Nine parameters: cut the image and position the clipped part on the canvas
- Img, one
<img>
Elements, or<canvas>
The element - Sx, the x coordinate of the source image
- Sy, the y coordinate of the source image
- Swidth, source image width
- Sheight, source image height
- X, represents the x coordinate of the drawing target
- Y, the y coordinate of the target to draw
- Width, the target width
- Height, target height
- Img, one
context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
Copy the code
7, shadow
- Attribute set
shadowColor
: Shadow color to draw, black by defaultshadowOffsetX
: The offset of the shadow relative to the shape or path’s x coordinate. Default: 0shadowOffsetY
: The offset of the shadow relative to the shape or path’s y-coordinate. Default: 0shadowBlur
: pixel, representing the amount of blur in the shadow. Default: 0
8, the gradient
createLineGradient()
Create a linear gradient- Parameters: starting x coordinate, starting Y coordinate, end x coordinate, end Y coordinate
- return
gradient
The instance- Instance using
addColorStop()
Specifies the color code for the gradient- Parameter: Color code position (0 to 1), CSS string
- Assign the instance to fillStyle or strokeStyle to draw the graph.
- Instance using
createRadialGradient()
Create a radial gradient- Parameters: starting circle center x, y and radius, ending point x, y and radius
- return
gradient
The instance- Instance using
addColorStop()
Specifies the color code for the gradient- Parameter: Color code position (0 to 1), CSS string
- Assign the instance to fillStyle or strokeStyle to draw the graph.
- Instance using
9, design,
- A repeated image used to fill and trace a figure
createPattern()
Passing in two parameters<img>
Elements (or<video>
,<canvas>
)- How to repeat an image: repeat, repeat-x, repeat-y, no-repeat
- The starting point of the pattern is the canvas origin (0, 0).
10. Image data
getImageData()
Get raw image data- Four parameters:
- To get the upper-left coordinate of the first pixel in the image data
- The pixel width and height to obtain
- Return an instance of ImageData with attributes width, height, and data
- Data is an array of pixel information for the elements of the image, represented by red, green, blue, and transparency (the first pixel is 0 to 3)
- Four parameters:
11, synthetic
-
globalAlpha
- The range 0-1 specifies the transparency of all drawn content. The default is 0
-
GlobalCompositionOperation, said the new drawing of the shape of the shape and context of the existing fusion
-
Source-over: default, new graphics drawn on top of old graphics.
-
Source-in: The new graph draws only the overlapped part of the original graph, and the rest of the canvas is transparent.
-
Source-out: The new graphics draw only the parts that do not overlap the original graphics, and the rest of the canvas is completely transparent.
-
Source-atop: The new graph only draws the overlapped part with the original one, and the original one is not affected.
-
Destination-over: The new graph is drawn under the original graph, and the overlap is visible only under the transparent pixels of the original graph.
-
Destination-in: The new graph is drawn below the original graph, leaving only the overlapping part of the canvas and the rest completely transparent.
-
Destination-out: the overlapping part of the new graph is completely transparent, and the rest of the original graph is not affected.
-
Destination-atop: The new graph is plotted below the original one, and the part that does not overlap with the new one is completely transparent.
-
Lighter: The pixel value of the overlapping part of the new graph and the original graph is added to lighten the part.
-
Copy: The new graphic will erase and completely replace the original graphic.
-
Xor: XOR calculation is performed on the pixels of the overlap between the new graph and the original graph
-
4, WebGL
1. WebGL context
let drawing = document.getElementById("drawing")
if(drawing.getContext) {
let gl = drawing.getContext("webgl")
if(gl) { ... }}Copy the code