Canvas notes
Introduction to the
The Canvas API provides a way to draw graphics using JavaScript and HTML's < Canvas > element. It can be used for animation, game graphics, data visualization, image editing, and real-time video processing. The Canvas API focuses primarily on 2D graphics. The WebGL API, which also uses the canvas> element, is used to draw hardware-accelerated 2D and 3D graphics.Copy the code
The canvas element
<canvas id="canvas" width="150" height="150"></canvas>
<canvas>Look and<img>The element is very similar, except that it does not have SRC and Alt attributes. In fact,<canvas>The tag has only two attributes, width and height. These are optional and are also set using DOM properties. When the width and height are not set, the canvas initializes 300 pixels wide and 150 pixels high. The element can be sized using CSS, but when drawn the image will scale to fit its frame size: if the CSS size is not proportional to the original canvas, it will distort. Note: If you draw a distorted image, try using the width and height properties as<canvas>Specify width and height explicitly, rather than using CSS.Copy the code
Alternative content
<canvas>Elements and<img>The difference with the tag is, like<video>.<audio>Or,<picture>Element, it's easy to define some alternative content. Since some older browsers (especially IE before Internet Explorer 9) or text browsers don't support the HTML element "canvas", you should always be able to display alternative content on these browsers. It's very simple: we're just<canvas>The replacement content is provided in the tag. Does not support<canvas>The browser will ignore the container and render backup content in it. And support<canvas>The browser will ignore the contents contained in the container and just render the canvas normally.<! -- For example, we can provide text description of canvas content or static picture corresponding to dynamically generated content, as follows: -->
<canvas id="canvas" width="150" height="150">Browsers do not support Canvas</canvas>
<canvas id="canvas" width="150" height="150">
<img src="Images/browser does not support.png" width="150" height="150" alt=""/>
</canvas>
<! </canvas> tag cannot be omitted
与 <img>The elements are different,<canvas>The element requires an end tag (</canvas>). If the closing tag does not exist, the rest of the document is considered a substitute and will not be displayed. If you don't need to substitute content, a simple<canvas id="foo" .></canvas>It is fully compatible with all canvas browsers.Copy the code
Render 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. We will focus on the 2D rendering context. Other kinds of contexts may provide different kinds of rendering; For example, WebGL uses OpenGL ES based 3D context ("experimental-webgl"). The canvas is initially blank. To display, the script first needs to find the render context and then draw on top of it. The <canvas> element has a method called getContext(), which is used to get the rendering context and its drawing functionality. GetContext () has only one argument, the format of the context. For 2D images, as in this tutorial, you can use CanvasRenderingContext2D.var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d'); The first line of code passes thedocumentThe.getelementById () method gets the DOM object for the <canvas> element. Once you have an element object, you can access the painting context by using its getContext() method.Copy the code
Based on the sample
// This simple example draws a line on the canvas
// 1. Get a reference to the HTML
/ / 2. Then, HTMLCanvasElement. GetContext () method to get the elements of the context, the image will be rendered in the later.
// 3. After getting the CTX object, draw a line from (200, 50) to (300, 50)
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.moveTo(200.50);
ctx.lineTo(300.50);
ctx.stroke();
Copy the code
Draw basic graphics
Draw a rectangle
Canvas provides three methods for drawing rectangles:
// 1. Draw a filled rectangle
fillRect(x, y, width, height)
// 2. Draw a rectangle border
strokeRect(x, y, width, height)
// 3. Clear the specified rectangle so that the clear part is completely transparent.
clearRect(x, y, width, height)
// The meaning of each parameter in the method provided above:
// x, y: represents the coordinates drawn on the canvas relative to the origin (upper left corner).
// width, height: represents the size of the rectangle
// Now use the above three functions
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillRect(50.100.100.100);
ctx.clearRect(75.125.50.50);
ctx.strokeRect(85.135.30.30);
Copy the code
Draw 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. A path, or even a subpath, is closed. Drawing graphs using paths requires some additional steps.1.First, you need to create the path starting point.2.You then use the draw command to draw the path.3.And then you close the path.4.Once the path is generated, you can render the shape by stroke or filling the path area./** Here are the functions to use: */
// Create a new path. After the path is generated, the graph drawing command is pointed to the path to generate the path.
beginPath()
// After closing the path, the graph drawing command points back to the context.
closePath()
// Use lines to draw shapes.
stroke()
// Generate solid graphics by filling the content area of the path.
fill()
Copy the code
Move the brush
A very useful function that doesn't actually draw anything and is part of the list of paths described above is moveTo(). Or you can imagine working on paper, moving the tip of a pen or pencil from one point to another.// Move the stroke to the specified coordinates x and y.
moveTo(x, y)
Copy the code
line
To draw a line, use the method lineTo().// Draw a line from the current position to the specified x and y positions.
lineTo(x, y)
Copy the code
The circular arc
To draw arcs or circles, we use the Arc () method. Of course you can use arcTo().// Draw an arc according to the given control point and radius, and then connect the two control points in a straight line.
arcTo(x1, y1, x2, y2, radius)
// Draw a radius circle with (x,y) as the center, starting from startAngle and ending from endAngle, in the direction given by anticlockwise (clockwise by default).Arc (x, y, RADIUS, startAngle, endAngle, anticlockwise) Radius indicates the radius. The startAngle and endAngle parameters define the starting and ending radians in radians. All of these are based on the X-axis. The anticlockwise parameter is a Boolean value. fortrue, is counterclockwise, otherwise clockwise.// Draw a circle
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.arc(100.100.50.0.Math.PI * 2.true);
ctx.stroke();
Copy the code
Quadratic Bessel curve and cubic Bessel curve
A very useful type of path is the Bezier curve. Quadratic and cubic Bezier curves are very useful for drawing complex and regular shapes.// Draw a quadratic Bessel curve, cp1x,cp1y is a control point, x,y is the end point.
quadraticCurveTo(cp1x, cp1y, x, y)
Cp1x,cp1y are control points 1, cp2x,cp2y are control points 2, x,y are end points.BezierCurveTo (CP1x, CP1Y, CP2x, CP2Y, X, Y) a quadratic Bezier curve has a start point, an end point, and a control point, while a cubic Bezier curve has two control points. The arguments x and y are end point coordinates in both methods. Cp1x,cp1y is the first control point in the coordinate, and CP2x,cp2y is the second control point in the coordinate.Copy the code
Path2D object
As we saw in the previous example, you can use a series of paths and paint commands to "paint" objects on the canvas. To 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() 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).
new Path2D(); // Empty Path object
new Path2D(path); // Clone the Path object
new Path2D(d); // Create a Path object from SVG
// Adds a path to the current path (possibly adding a transformation matrix).
Path2D.addPath(path [, transform])
/ / sample
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const rectangle = new Path2D();
rectangle.rect(10.10.50.50);
ctx.stroke(rectangle);
ctx.fill(rectangle);
Copy the code
SVG paths
Another powerful feature of the new Path2D API is the use of SVG Path Data to initialize paths on the canvas. This will allow you to retrieve paths and reuse them as SVG or Canvas. This path will first move to the point (M10)10) and then move horizontally80A unit (h80), and then move down80A unit (v80), then move to the left80H minus80), and then back to the starting point (z)./ / sample
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
var p = new Path2D("M10 10 h 80 v 80 h -80 Z");
ctx.fill(p);
Copy the code
Styles and colors
Color Colors
If we want to color a graph, there are two important properties that can do this:// Set the fill color of the graph.
fillStyle = color
// Set the color of the shape outline.
strokeStyle = color
// Example: These fillStyle values are 'orange'
ctx.fillStyle = "orange";
ctx.fillStyle = "#FFA500";
ctx.fillStyle = "RGB (255165, 0)";
ctx.fillStyle = "Rgba (255165, 1)"; Note: Once you set strokeStyle or fillStyle, this new value will become the default value for the newly drawn graphics. If you want to give each graphic a different color, you need to reset fillStyle or strokeStyle.Copy the code
The Transparency of Transparency
In addition to drawing solid color graphics, we can also use canvas to draw semi-transparent graphics. By setting the globalAlpha property or using a translucent color for the outline or fill style.// This property affects the transparency of all graphics in the canvas. Valid values range from 0.0 (fully transparent) to 1.0 (fully opaque). The default is 1.0
globalAlpha = 1.0
Copy the code
Linear Line styles
Lines can be styled through a series of properties// Set the line width.
lineWidth = value
// Set the end of the line style.
lineCap = type
// Set the style of the line and the indirect line.
lineJoin = type
// Limit 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.
miterLimit = value
// Returns an array containing the current dashed line style and a non-negative even length.
getLineDash()
// Sets the current dashed line style.
setLineDash(segments)
// Set the starting offset of the dashed style.
lineDashOffset = value
Copy the code
lineWidth
attribute
This property sets the thickness of the current drawing line. Attribute value must be positive. The default value is 1.0. Line width is the width from center to sides of a given path. In other words, draw half the line width on each side of the path. Because the coordinates of the canvas do not correspond directly to the pixels, special care should be taken when obtaining accurate horizontal or vertical lines.Copy the code
lineCap
attribute
The value of the lineCap property determines what the end points of a line segment look like. It can be one of three: butt, round, or square. The default is butt.Copy the code
lineJoin
attribute
The value of the lineJoin attribute determines how the two line segments join in the graph. It can be one of these three: round, bevel and miter. The default is miter.Copy the code
miterLimit
attribute
The miterLimit attribute is used to set the maximum distance between the epitaxial intersection and the join point. If the distance is greater than this value, the join effect becomes a bevel. Note that the maximum miterLimit length (i.e. intersection distance) is the product of the measured line width of the current coordinate system and the value of this miterLimit attribute (HTML <canvas> defaults to 10.0), so miterLimit can be set separately and is not affected by display scale changes or any affine transformations: it only affects the effectively drawn shape of the edge of the lineCopy the code
Use a dotted line
Use the setLineDash method and the lineDashOffset attribute to style dashed lines. The lineDashOffset property sets the starting offset.// 4 represents the line length and 2 represents the spacing
ctx.setLineDash([4.2]);
Copy the code
The gradient Gradients
Just like normal drawing software, we can fill or stroke with linear or radial gradients. We create a New canvasGradient object using the following method and assign the fillStyle or strokeStyle attribute to the graph.The createLinearGradient method takes four parameters, representing the beginning and end of the gradient (x1,y1) and (x2,y2).
createLinearGradient(x1, y1, x2, y2)
// The createRadialGradient method takes six parameters. The first three parameters define a circle with the origin of (x1,y1) and radius r1, and the last three parameters define another circle with the origin of (x2,y2) and radius R2.
createRadialGradient(x1, y1, r1, x2, y2, r2)
The position parameter 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.).
gradient.addColorStop
/ / sample
const lineargradient = ctx.createRadialGradient(100.100.0.100.100.50);
lineargradient.addColorStop(0.'#fff');
lineargradient.addColorStop(1.'#50c5f1');
ctx.fillStyle = lineargradient;
ctx.arc(100.100.50.0.Math.PI * 2.true);
ctx.fill();
Copy the code
Patterns and Patterns
// 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.CreatePattern (image, type) Note: Use canvas object as image parameter in Firefox1.5 (Gecko 1.8) is invalid. Note: Unlike drawImage, you need to make sure the image object has been loaded, otherwise the image might not look right./ / sample
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = () = > {
const ptrn = ctx.createPattern(img, 'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0.0.400.400);
}
Copy the code
Shadow we
// 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.
shadowOffsetX = float
shadowOffsetY = 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.
shadowBlur = float
// shadowColor is the standard CSS color value used to set the shadowColor effect. The default is full transparent black.
shadowColor = color
// Text shadow example
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.shadowColor = 'rgb(193, 193, 193)';
ctx.shadowBlur = 3;
ctx.font = "40px Microsoft Yahei";
ctx.fillText('Hello Canvas'.100.100);
Copy the code
Draw text
Canvas provides two methods for rendering text// Fill the specified text at the specified (x,y) position. The maximum width to draw is optional.
fillText(text, x, y [, maxWidth])
// Draws a text border at the specified (x,y) position. The maximum width to draw is optional.
strokeText(text, x, y [, maxWidth])
Copy the code
Styled text
// 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.
font = value
// Text alignment options. Optional values include: start, end, left, right, or center. The default value is start.
textAlign = value
// Baseline alignment options. Optional values include: top, Hanging, middle, alphabetic, ideographic, and bottom. The default value is alphabetic.
textBaseline = value
// Text direction. Possible values include: LTR, RTL, inherit. The default value is inherit.
direction = value
Copy the code
Predict the amount of text width
The following methods can give you a way to measure text when you need more detail.// Will return the width of a TextMetrics object, the pixel, and other attributes that reflect the nature of the text.
measureText()
// The following code snippet shows how to measure text to get its width:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const text = ctx.measureText("Hello");
console.log(text.width);
Copy the code
image
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. External images in any format supported by the browser can be used, such as PNG, GIF, or JPEG. You can even source images generated by other Canvas elements on the same page.Copy the code
Gets the image that needs to be drawn
The Canvas API can use one of these types as a source for images:// These images are constructed by the Image() function, or any element
HTMLImageElement
// Use an HTML
HTMLVideoElement
// You can use another
HTMLCanvasElement
// 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.
ImageBitmap
// These sources are uniformly referenced by the CanvasImageSource type.
Copy the code
Draw pictures
Once we have the source graph object, we can use the drawImage method to render it to the canvas. The drawImage method has three forms:// where image is the image or canvas object, x and y are its starting coordinates in the target canvas.
drawImage(image, x, y)
// This method takes two additional arguments: width and height, which control how much to scale when drawing to the canvas
drawImage(image, x, y, width, height)
// The first argument is the same as the others, which are references to an image or another canvas.
// For the other 8 parameters, please refer to the diagram on the right.
// The first four define the slice position and size of the image source, and the last four define the slice target display position and size.
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
Copy the code
Controls the zoom behavior of the image
Overly zooming an image may cause it to blur or become pixelated. You can control whether to use the smoothing algorithm when scaling the image by using the imageSmoothingEnabled property of the drawing environment. The default value istrueThat is, smooth zooming is enabled. You can also disable this function like this: CTX. MozImageSmoothingEnabled =false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
Copy the code
Deformation Transformations
State saving and recovery
// Save all the states of the canvas
save()
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.Restore () You can call the save method as many times as you want. Each time the restore method is called, the last saved state is popped from the stack and all Settings are restored.Copy the code
Mobile Translating
The translate method takes two arguments. X is the left/right offset and y is the up/down offset, as shown on the right.
translate(x, y)
Copy the code
Rotate the Rotating
// This method takes only one argument: Angle, which is clockwise and measured in radians.Rotate (Angle) The center point of rotation is always the origin of the canvas. To change it, use the translate method.Copy the code
Zoom Scaing
We use it to increase or decrease the number of pixels in the canvas, to shrink or enlarge shapes and bitmaps.The scale method scales the horizontal and vertical units of the canvas. Both parameters are real numbers and can be negative. X is the horizontal scaling factor, y is the vertical scaling factor. If it is smaller than 1, the graph will be shrunk, and if it is larger than 1, it will be enlarged. The default value is 1, which is the actual size.
scale(x, y)
Copy the code
Deformation Transforms
// This method multiplicates the current deformation matrix by a matrix based on its own parameters
transform(a, b, c, d, e, f)
// The arguments to this function are as follows:
// Horizontal scaling
a (m11)
// Vertical tilt offset
b(m12)
// Horizontal tilt offset
c(m21)
// Vertical scaling
d(m22)
// Horizontal movement
e(dx)
// Vertical movement
f(dy)
// This method resets the current transform matrix to the identity matrix, and then calls the transform method with the same parameters. If any of the arguments are infinite, then the deformation matrix must also be marked as infinite, or an exception will be thrown. Basically, this method cancels the current deformation and then sets it to the specified deformation in one step.
setTransform(a, b, c, d, e, f)
// Reset the current transform to the identity matrix, which is the same as calling ctx.setTransform(1, 0, 0, 1, 0, 0);
resetTransform()
Copy the code
Composition and cutting
Combination of Compositing
// This property sets the masking strategy to use when drawing new graphics. Its value is a string identifying 12 masking methods.
globalCompositeOperation = type
// Optional parameters:
// This is the default setting and draws new graphics on top of the existing canvas context.
'source-over'
// New graphics are only drawn where the new graphics and the target canvas overlap. Everything else is transparent.
'source-in'
// Draw a new shape where it does not overlap the existing canvas contents.
'source-out'
// New graphics are drawn only where they overlap the contents of the existing canvas.
'source-atop'
// Draw a new shape behind the existing canvas content.
'destination-over'
// The existing canvas content remains where the new graphic and the existing canvas content overlap. Everything else is transparent.
'destination-in'
// Keep the existing content where the new graphics do not overlap.
'destination-out'
// The existing canvas retains only the overlap with the new graphics, which are drawn behind the canvas content.
'destination-atop'
// The color of two overlapping shapes is determined by adding the color values.
'lighter'
// Display only new graphics.
'copy'
// The rest of the image is transparent beyond the overlap and normal drawing.
'xor'
// Multiply the top pixel by the corresponding bottom pixel, resulting in a darker picture.
'multiply'
// The pixels are inverted, multiplied, and inverted again, resulting in a brighter picture.
'screen'
The parts that are dark are darker and the parts that are light are lighter.
'overlay'
// Keep the darkest pixels between the two layers.
'darken'
// Keep the brightest pixels between the two layers.
'lighten'
// Divide the bottom layer by the inverse of the top layer.
'color-dodge'
// Divide the inverted bottom layer by the top layer, and then reverse the result.
'color-burn'
// A combination of multiply and screen is similar to overlay, but the top and bottom layers are switched.
'hard-light'
// Subtract the bottom layer from the top layer or vice versa to get a positive value.
'soft-light'
// A soft version of hard-light. Pure black or white does not lead to pure black or white.
'difference'
// Similar to difference, but with lower contrast.
'exclusion'
// Retain the brightness (Luma) and chroma of the bottom layer, while adopting the hue (hue) of the top layer.
'hue'
// Retain the brightness (luma) and hue (hue) of the bottom layer, while adopting the chroma of the top layer.
'saturation'
// Retain the brightness of the bottom layer (Luma), while adopting the hue and chroma of the top layer.
'color'
// Keep the bottom hue (hue) and chroma (chroma), while using the top layer brightness (luma).
'luminosity'
Copy the code
Cutting path
The cropping path is similar to the ordinary canvas graph, except that it acts as a mask to hide unwanted parts.// Convert the path currently being built to the current clipping path.
clip()
/ / sample
ctx.fillRect(100.50.200.200);
ctx.arc(200.150.75.0.Math.PI * 2.true);
ctx.clip();
ctx.fillStyle = 'green';
ctx.fillRect(100.50.200.200);
Copy the code
Basic animation
The basic steps of animation
/** You can draw a frame by following these steps: */
1.Clear the Canvas unless the next drawing will fill the canvas completely (for example, the background), you need to clear everything. The easiest way to do this is to use the clearRect method.2.Save the Canvas State If you want to change Settings that change the canvas state (style, deformation, etc.) and keep the original state for every frame you draw, you need to save it first.3.Animated Shapes is the step to redraw animation frames.4.If you have saved the canvas state, you can restore it first and then redraw the next frame.Copy the code
Update the canvas
// When the interval is set, function is executed periodically.
setInterval(function.delay) (en-US) // Execute the function after the set timesetTimeout(function, delay) (en-US) // Tell the browser that you want to execute an animation, and ask the browser to execute a specific function to update the animation before redrawing.requestAnimationFrame(callback)
Copy the code