What is?

Canvas is an HTML element that can be used to draw graphics using JS scripts

For what?

Can draw ICONS, graphics, pictures

How does it work?

Basic usage

  1. Prepare a<canvas id="xxx"></canvas>The label
  2. Get the DOM object,let canvas=document.getElementById('xxx')
  3. Get the canvas rendering context,let ctx=canvas.getContext('2d')

Canvas tag does not have SRC and Alt, and only width and height attributes can be used to insert backup content. The canvas that supports canvas will be displayed. Browsers that do not support Canvas will ignore canvas and display the inserted backup content, so it must be closed

Draw the shape

  1. grid

Canvas elements have a grid by default, and each cell is equivalent to a Canvas pixel

  1. rectangular

Canvas only supports two forms of graph drawing: rectangle and path (i.e. line segment) there are three ways to draw a rectangle:

  • fillRect(x, y, width, height)

Draws a filled rectangle

  • strokeRect(x, y, width, height)

Draws the border of a rectangle

  • clearRect(x, y, width, height)

Clear the specified rectangle so that the clear portion is fully transparent. 3. Path (Line segment)

  • beginPath()

Create a new path. After the path is generated, the graph drawing command is pointed to the path to create the path.

  • closePath()

After drawing, the graph drawing command is redirected to the context after the path is closed.

  • stroke()

Use lines to draw the outline of a graph.

  • fill()

Generates solid graphics by filling the content area of the path. If you call Fill, you don’t need to call closePath. It closes automatically

Drawing commands

  1. moveTo(x,y)

Move the stroke and place it relative to the starting point in the upper left corner

  1. lineTo(x,y)

Draws a line from the current position to the specified coordinate point

  1. arc(x, y, radius, startAngle, endAngle, anticlockwise)

Draw a radius arc (circle) with (x,y) as the center, starting with startAngle and ending with endAngle, in the direction given by anticlockwise (clockwise by default).

ArcTo (x1, y1, x2, y2, radius) can also be used to draw an arc for the fixed point and radius, and then connect the two control points in a straight line

  1. Quadratic Bessel curve and cubic Bessel curve
  • quadraticCurveTo(cp1x, cp1y, x, y)

Draw a quadratic Bessel curve, cp1x,cp1y as a control point, x,y as the end point.

  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Draw Bessel curves three times, with cp1x and CP1y as control points 1, cp2x and cp2y as control points 2, and x and y as end points.

5.Path2D An object used to cache or record drawing commands

    var ctx = canvas.getContext('2d');
    var rectangle = new Path2D();
    rectangle.rect(10.10.50.50);

    var circle = new Path2D();
    circle.moveTo(125.35);
    circle.arc(100.35.25.0.2 * Math.PI);

    ctx.stroke(rectangle);
    ctx.fill(circle);
Copy the code
  1. SVG paths

Var p = new Path2D(“M10 10 h 80 v 80 h-80 Z”); It means we move to the point (M10 10) and then we move horizontally 80 (H 80), then down 80 (V 80), then left 80 (H-80), and then back to the starting point (z).

Add styles and colors

Set the color

  1. fillStyle=color

StrokeStyle =color Set the contour color of the graphics. 3. Transparency

  • Global transparency: globalAlpha = transparencyValue
  • Transparency can also be set directly with RGBA

Set the linear

  1. lineWidth = value

Set the line width. 2. LineCap = type Sets the end of the line style. 3. LineJoin = type Sets the style of line and indirect line. 4. MiterLimit = value Specifies the maximum length at which two lines intersect. The so-called intersection length (miter length) is the length from the inner corner to the outer corner of the line where it meets. 5. GetLineDash () returns an array containing the current dashed line style and a non-negative even length. 6. SetLineDash (segments) Sets the current dashed line style. 7. LineDashOffset = value Sets the starting offset of the dashed line style.

Set the gradient

  1. createLinearGradient(x1, y1, x2, y2)

The createLinearGradient method takes four parameters representing the beginning and end of the gradient (x1,y1) and (x2,y2).

Var that lineargradient = CTX. CreateLinearGradient,0,150,150 (0);

  1. createRadialGradient(x1, y1, r1, x2, y2, r2)

The createRadialGradient method takes six parameters. The first three parameters define a circle with the origin of (x1,y1) and radius of R1, and the last three parameters define another circle with the origin of (x2,y2) and radius of R2.

Var radialgradient = CTX. CreateRadialGradient,75,0,75,75,100 (75);

After creating the canvasGradient object, you can color it with gradient.addColorStop(position, color).

The addColorStop method takes two arguments. The position argument must be a number between 0.0 and 1.0, representing the relative position of the color in the gradient. For example, 0.5 means the color will appear right in the middle. The color parameter must be a valid CSS color value (e.g. #FFF, rgba(0,0,0,1), etc.).

Set pattern Patterns

  • createPattern(image, type)

The method takes two arguments. Image can be a reference to an Image object, or another Canvas object. Type must be one of the following string values: repeat, repeat-x, repeat-y, and no-repeat.

  var ctx = document.getElementById('canvas').getContext('2d');

  // Create a new image object to use as a pattern
  var img = new Image();
  img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
  img.onload = function() {

    // Create a pattern
    var ptrn = ctx.createPattern(img, 'repeat');
    ctx.fillStyle = ptrn;
    ctx.fillRect(0.0.150.150);
Copy the code

Set Shadow Shadows

  1. shadowOffsetX = float

ShadowOffsetX and shadowOffsetY are used to set the extension distance of the shadow on the X and Y axes. They are not affected by the transformation matrix. A negative value means the shadow will go up or left, and a positive value means it will go down or right, both of which default to 0.

  1. shadowOffsetY = float

ShadowOffsetX and shadowOffsetY are used to set the extension distance of the shadow on the X and Y axes. They are not affected by the transformation matrix. A negative value means the shadow will go up or left, and a positive value means it will go down or right, both of which default to 0.

  1. shadowBlur = float

The value of shadowBlur is not linked to the number of pixels and is not affected by the transformation matrix. The default value is 0.

  1. hadowColor = color

ShadowColor is the standard CSS color value used to set the shadowColor effect. The default is full transparent black.

Setting the Fill Rule

Fill (or clip and isPointinPath) selects a fill rule that determines whether a place is filled based on whether it is outside or inside the path

  1. “nonzero”
  2. “evenodd”

Draw text

  1. fillText(text, x, y [, maxWidth])

2. StrokeText (text, x,y [, maxWidth]) Draws a text border at the specified (x,y) position. The maximum width is optional.

There is also a set of style properties:

  1. font = value

The style we are currently using to draw text. This string uses the same syntax as the CSS font property. The default font is 10px sans-serif.

  1. textAlign = value

Text alignment options. Optional values include: start, end, left, right, or Center. The default value is start.

  1. textBaseline = value

Optional values include top, Hanging, middle, alphabetic, ideographic, and bottom. The default value is alphabetic.

  1. direction = value

Text direction. Possible values include: LTR, RTL, inherit. The default value is inherit.

And measureText() retrieves the text width, which returns the width of a TextMetrics object and the pixel it is in, attributes that reflect text properties.

Operating picture

There are many types of elements that can be used as sources for images

  1. HTMLImageElement

These images are constructed by the Image() function, or whateverThe element

  1. HTMLVideoElement

Using an HTML element as your image source, you can grab the current frame from the video as an image

  1. HTMLCanvasElement

You can use another element as your image source.

  1. ImageBitmap

This is a high-performance bitmap that can be drawn with low latency, and it can be generated from all of the above sources and several others.

Basic use:

  1. drawImage(image, x, y, width, height)

Where image is the image or canvas object, x and y are its starting coordinates in the target canvas. Width and height are used to control scaling

  1. drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

The first argument is the same as the others, and is a reference to either an image or another canvas. The other 8 parameters, the first 4 are to define the slice position and size of the image source, the last 4 are to define the target display position and size of the slice.

Overscaling an image can cause the image to blur or become pixelated, and you can control whether to use a smoothing algorithm when scaling the image by using the imageSmoothingEnabled property of your drawing environment. The default value is true, that is, smooth scaling is enabled. It can also be disabled with imageSmoothingEnabled=false

deformation

State saving and recovery

  1. save()

Save all the states of the canvas

  1. restore()

Restore restores the canvas state

Deformation related API

  1. mobiletranslate(x,y)
  2. rotate(angle)
  3. scale(x,y)
  4. transform(a,b,c,d,e,f)
    • a (m11)Horizontal scaling
    • b(m12)Vertical tilt deviation
    • c(m21)Oblique deviation in the horizontal direction
    • d(m22)Vertical scaling
    • e(dx)Horizontal movement
    • f(dy)Vertical movement
  5. setTransform(a,b,c,d,e,f)
    • Cancels the current deformation and then sets it to the specified deformation
  6. resetTransform()Literally, reset

Composition and clipping

See MDN effect directly: composition and cropping MDN

Basic animation

Steps:

  1. Empty canvas

Unless the next drawing is going to fill the canvas completely (like the background), you need to clear everything. The easiest way to do this is to use the clearRect method.

  1. Save the Canvas state

If you want to change Settings that change the canvas state (styles, morphs, etc.) and keep the canvas state in its original state every frame, you need to save it first.

  1. Animated Shapes

This is the step to redraw the animation frame.

  1. Restore canvas state

If you have saved the canvas state, you can restore it first and then redraw the next frame.

Use setInterval(), setTimeout(), requestAnimationFrame() to manipulate the animation

RequestAnimationFrame () typically performs 60 callbacks per second

Specific practice: MDN advanced animation

Pixel operations

  • The ImageData object stores the real pixel data of the Canvas object, including width, height and data
  • Saving the image toDataURL(imageType,quality) will create a data link with image resolution of 96dpi. Quality0 to 1

reference

  • Canvas tutorial MDN