introduce
WebKit was first introduced by Apple as the Dashboard for Mac OS X. Canvas is a new element of HTML5 that can be used to draw graphics using scripts in JavaScript. For example, it can be used to draw graphics, make photos, create animations, play interactive games, and even do real-time video processing or rendering.
Basic usage
Canvas is an element. Of course, it has attributes common to elements, such as ID and class.
The rendering context
The Canvas element creates a fixed-size canvas that exposes one or more render contexts that can be used to draw and process the content to be displayed.
Let canvas = document.querySelector('#canvas') let CTX = canvas.getContext('2d')Copy the code
Check support
If (canvas.getContext) {// support} else {// not support}Copy the code
Draw the shape
rectangular
FillRect (x, y, width, height) draws a filled rectangle. StrokeRect (x, y, width, height) draws a rectangle’s border. Height clears the specified rectangle so that the cleared portion is fully transparent. Often used to clean canvas.
The path
The basic element of the graph is the path. A path is a collection of points of different shapes connected by line segments or curves of different colors and widths.
- First, you need to create the path starting point.
- You then use the draw command to draw the path.
- And then you close the path.
- Once the path is generated, you can render the shape by stroke or filling the path area.
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 the path is closed, the graph drawing command points back to the context.
The stroke () – outline
Use lines to draw the outline of a graph.
The fill () – as a whole
Generates solid graphics by filling the content area of the path.
PS: Fill closes automatically and stroke does not.
MoveTo (X, Y) — Moves strokes
Moves the stroke to the specified coordinates X and y.
When canvas initializes or beginPath() is called, you usually use the moveTo() function to set the starting point. We can also use moveTo() to draw discontinuous paths
LineTo (x, y) — a line
Draws a line from the current position to the specified x and y positions.
Arc (x, Y, RADIUS, startAngle, endAngle, anticlockwise) — An arc
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)
Draw an arc according to the given control point and radius, and then connect the two control points in a straight line.
Radians =(math.pi /180)*degrees
QuadraticCurveTo (CP1x, CP1Y, X, Y) — Quadratic Bezier curves
Draw a quadratic Bessel curve, cp1x,cp1y as a control point, x,y as the end point.
BezierCurveTo (CP1x, CP1Y, CP2x, CP2Y, x, Y) — Cubic Bezier curves
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.
PS: Bezier curves always start with the starting path. In fact, the quadratic Bezier curve is controlled by 3 points, and the NTH Bezier curve is controlled by N +1 points.
Wiki-bezier curve
Extra method to draw a rectangle
rect(x, y, width, height)
Draw a rectangle with upper-left coordinates (x,y), width and height.
Path2D objectTo simplify code and improve performance, Path2D objects can now be used in newer browsers to cache or record drawing commands so you can quickly review the path.
Path2D()
Path2D() returns a newly initialized Path2D object (possibly a path as a variable — create a copy of it, or a string containing SVG Path data as a variable).
Path2D.addPath(path [, transform])
Adds a path to the current path (possibly adding a transformation matrix).Var p = new Path2D("M10 10 h 80 v 80 h-80 Z");Copy the code
Use styles and colors
Color Colors
FillStyle = color Sets the fill color of the graphic. StrokeStyle = color Sets the color of the shape outline. PS: Orange, # FFA500, RGBA (255, 165, 0, 1), HSL (360, 50%, 50%), HSLA (360, 50%, 50%, 1)
The Transparency of Transparency
GlobalAlpha = transparencyValue This property affects the transparency of all graphics in the canvas. Valid values range from 0.0 (fully transparent) to 1.0 (completely opaque). The default is 1.0. CTX. StrokeStyle = “rgba (255,0,0,0.5)”; CTX. FillStyle = “rgba (255,0,0,0.5)”;
Linear Line styles
Lines can be styled through a series of properties. LineWidth = value sets the lineWidth. Line width is the sum of the distances from the center to both sides of a given path. In other words, draw half the line width on each side of the path. LineCap = type Sets the end of the line style. Butt, round and square. The default is butt. LineJoin = type Sets the style of the line and the adjacent line. Round, Bevel and Miter. The default is miter. 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. GetLineDash () returns an array containing the current dotted line style and a non-negative even length. [A, b] A is a solid line, b is blank, and so on. SetLineDash (segments) sets the current dashed line style. LineDashOffset = value Sets the starting offset for the dashed line style.
Gradient Gradients (new gradient object)
Linear gradient
The createLinearGradient method takes four parameters, representing the start (x1,y1) and end (x2,y2) of the gradient.
Radial gradient
Let radialgradient = createRadialGradient(x1, y1, R1, x2, y2, R2) createRadialGradient method accepts 6 parameters, the first three are defined with (x1,y1) as the origin, The last three parameters define another circle with the origin of (x2,y2) and radius of R2. Gradient. addColorStop(position, color) The addColorStop method takes two arguments. The position argument must be a value 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.).
Patterns and Patterns
CreatePattern (image, type) This 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. You need to make sure the image object is onloaded, otherwise the image might not look right.
Shadow we
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. 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. ShadowBlur = float shadowBlur is used to set the blur degree of the shadow. The value is not linked to the number of pixels and is not affected by the transformation matrix. The default value is 0. ShadowColor is a standard CSS color value used to set the shadowColor effect. The default is full transparent black.
Canvas filling rule
When we use fill (or clip and isPointinPath) you can select a fill rule that determines whether a certain place is filled based on whether it is inside or outside the path. This is useful when you intersect your own path or when paths are nested. Nonzero: default value evenodd
Draw text
Canvas provides two methods for rendering text: FillText (text, x,y [, maxWidth]) fills the specified text at the specified (x,y) position. The maximum width to draw is optional. StrokeText (text, x,y [, maxWidth]) draws a text border at the specified (x,y) position. The maximum width to draw is optional.
Styled text
Font = value The style we currently use to draw text. This string uses the same syntax as the CSS font property. The default font is 10px sans-serif. TextAlign = Value Text alignment option. Optional values include: start, end, left, right, or center. The default value is start. TextBaseline = Value Baseline alignment option. Optional values include: top, Hanging, middle, alphabetic, ideographic, and bottom. The default value is alphabetic. Direction = value Specifies the text direction. Possible values include: LTR, RTL, inherit. The default value is inherit.
Advanced text measurement
The following methods can give you a way to measure text when you need more detail. MeasureText () returns the width and pixel of a TextMetrics object, attributes that reflect text properties. var text = ctx.measureText(“foo”); // TextMetrics object text.width; / / 16;
Using images
One of the more interesting features of Canvas is the ability to manipulate images. Can be used for dynamic image composition or as graphical backgrounds, game interfaces (Sprites), etc. Introducing an image to canvas requires the following two basic steps:
- Get a reference to the HTMLImageElement object or another Canvas element as the source. You can also use the image by providing a URL (see example)
- Draw the image onto the canvas using the drawImage() function
Get the image you need to draw
HTMLImageElement
These images are constructed by the Image() function, or whateverThe element
HTMLVideoElement
Using an HTML element as your image source, you can grab the current frame from the video as an image
HTMLCanvasElement
You can use another element as your image source.
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.
PS: These sources are uniformly referenced by the CanvasImageSource type. - The images document using the same page. Images collection document. The getElementsByTagName () method of the document. The getElementById () to obtain the images
- With the crossOrigin attribute on the HTMLImageElement, you can request images from other domains to be loaded.
- Create an image from zero (onload is required to ensure that the image is loaded)
var img = new Image(); // Create a <img> element img. SRC = 'myimage.png '; // Set the image source address
- Embed image via data: URL
img.src = 'data:image/gif; base64,... '
- Using video frames
return document.getElementById('myvideo');
Draw pictures
drawImage(image, x, y)
Where image is the image or canvas object, x and y are its starting coordinates in the target canvas.Zoom Scaling
drawImage(image, x, y, width, height)
This method has two additional arguments: width and height, which control how much to scale when drawing to the canvasSlice Slicing
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 are best referred to the diagram on the right. The first 4 parameters define the slice position and size of the image source, and the last 4 parameters define the target display position and size of the slice.Controlling image scaling behavior
Gecko 1.9.2 introduced the mozImageSmoothingEnabled property, which does not scale smoothly when the value is false. The default is true.
cx.mozImageSmoothingEnabled = false;
Deformation Transformations
Saving and Restoring State Saving and Restoring State
save()restore()
The save and restore methods are used to save and restore the canvas state without arguments. The Canvas state is a snapshot of all the styles and distortions applied to the current screen.
PS: Canvas state is stored in the stack. Whenever save() is called, the current state is pushed to the stack for saving.Painting states include:
Deformation of the current application (i.e. move, rotate, and scale, see below)
strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, ShadowBlur, shadowColor, globalCompositeOperation values
Current Clipping PathMobile Translating
Let’s start with the Translate method, which moves the canvas and its origin to a different location.
translate(x, y)
The Translate method takes two arguments. X is the left/right offset and y is the up/down offset, as shown on the right.
It is a good practice to preserve the state before doing the transformation.
Reference: MDN-Canvas