CanvasRenderingContext2D
CanvasRenderingContext2D is the “Canvas 2D rendering context”, which can be understood as the context in the following code.
var canvas = document.querySelector('canvas'); var context = canvas.getContext('2d'); Copy the code
Context exposes a large number of API properties and methods, which can be used to draw text, graphics, pixel processing, etc., and can be said to be the core of 2D Canvas application.
Draw a rectangle
CanvasRenderingContext2D. ClearRect () to remove the specified rectangle of all pixels in the region information for initial color (usually a transparent). CanvasRenderingContext2D. FillRect () rectangle filling, can fill color, gradient, pattern, etc. Rectangular stroke CanvasRenderingContext2D. StrokeRect ().
Draw text
Fill CanvasRenderingContext2D. FillText () text, and can be filled with pure color, gradient, or pattern. Text stroke CanvasRenderingContext2D. StrokeText (). Text CanvasRenderingContext2D. MeasureText () measurement. Return a TextMetrics object whose width property is the width occupied by the character.
Line style
CanvasRenderingContext2D. Our lineWidth line width, and the main usage scenario is stroke, the default width is 1.0, support for decimal. The style of the CanvasRenderingContext2D. LineCap line endpoint. The following properties are supported: butt (default, broken head, uncapped cap), round (round cap), and square (square cap). CanvasRenderingContext2D. LineJoin the style of the line is around the corner. The following values are supported: miter (default, sharp), round (round), and bevel (straight). CanvasRenderingContext2D. MiterLimit Angle limit ratio. The sharp Angle of the line, if not limited, will be very long if the line is thick and the Angle is small. Therefore, a limit ratio is needed. The default is 10. Numerical CanvasRenderingContext2D. GetLineDash () returns the dotted line. The return value is an array of the even number CanvasRenderingContext2D. SetLineDash () sets the line as the dotted line. CanvasRenderingContext2D. LineDashOffset starting offset Settings dotted line.
The text style
CanvasRenderingContext2D. The font set font related styles, including font size, font information. The default is 10px sans-serif. CanvasRenderingContext2D. TextAlign set level text alignment. Supported values are start (default), end, left, right, and Center. CanvasRenderingContext2D. TextBaseline set baseline text alignment. Supported values are: top, hanging, Middle, alphabetic (default), ideographic, bottom. CanvasRenderingContext2D. Direction set text direction. The supported property values include inherit (default), LTR and RTL.
Fill and stroke
CanvasRenderingContext2D fillStyle fill style. The default is #000000 pure black. Fill CanvasRenderingContext2D. The fill (). CanvasRenderingContext2D. StrokeStyle stroke style. The default is #000000 pure black. CanvasRenderingContext2D. Stroke (stroke).
The gradient related
The methods associated with gradients in Canvas are to create linear gradients and radial gradients.
CanvasRenderingContext2D. CreateLinearGradient () to create a linear gradient. CanvasRenderingContext2D. CreateRadialGradient () to create a radial gradient.
Design related
The pattern related method in Canvas is the create pattern Object method.
CanvasRenderingContext2D. CreatePattern () to create designs. The graphic content can be an image, a < Canvas > element, or a gradient. This method returns a CanvasPattern object.
Shadow related
The following are the properties associated with shadows in the Canvas.
CanvasRenderingContext2D. ShadowBlur fuzzy shadow size. The default value is 0. CanvasRenderingContext2D. ShadowColor shadow color. The default value is all transparent black. Horizontal offset size CanvasRenderingContext2D. ShadowOffsetX shadow. The default value is 0. CanvasRenderingContext2D shadowOffsetY shadow size of vertical migration. The default value is 0.
Draw the path
The following methods can be used to handle path objects.
CanvasRenderingContext2D. BeginPath () to start a new path. A path CanvasRenderingContext2D. ClosePath () closed. CanvasRenderingContext2D. MoveTo () path map starting point. CanvasRenderingContext2D. LineTo draws lines () to the specified coordinates to the point. CanvasRenderingContext2D. BezierCurveTo beisaier curve drawing () to the specified coordinates to the point. CanvasRenderingContext2D. QuadraticCurveTo secondary beisaier curve drawing () to the specified coordinates to the point. CanvasRenderingContext2D. Arc () draw arc (including round). CanvasRenderingContext2D. ArcTo () draw arc, and before points are connected by a straight line. Draw a rectangle path CanvasRenderingContext2D. The rect (). CanvasRenderingContext2D. The ellipse () draw the elliptical path. CanvasRenderingContext2D. Clip () to create a clipping path, after drawing the path only in the inside of the display.
The position detection
Whether CanvasRenderingContext2D. IsPointInPath () the current point within the specified path. CanvasRenderingContext2D. IsPointInStroke () whether the current point on the edge of the specified path tracing.
transform
Rotation scale and other transformation methods.
Rotate CanvasRenderingContext2D. Rotate (). Zoom CanvasRenderingContext2D. Scale (). Displacement CanvasRenderingContext2D. Translate (). CanvasRenderingContext2D. The transform () based on the matrix transformation matrix again. CanvasRenderingContext2D. SetTransform () directly to reset to the current set of matrix transformation.
Transparency and hierarchy
One controls global transparency, while the other can change hierarchies, set blending modes, and implement masks.
CanvasRenderingContext2D globalAlpha global transparency. CanvasRenderingContext2D. GlobalCompositeOperation set the graphic overlay time of mixed mode, which can be used to change superposition of map elements, namely hierarchy.
Pictures and Pixels
Drawing pictures and image pixel information processing method.
CanvasRenderingContext2D. DrawImage () pictures drawn on the canvas. CanvasRenderingContext2D. CreateImageData () to create a new blank ImageData object. CanvasRenderingContext2D. GetImageData () to obtain the Canvas of the Canvas ImageData object to set area. CanvasRenderingContext2D. PutImageData () a given ImageData object used in the Canvas on the Canvas.
The Canvas state
Canvas state management has several methods.
CanvasRenderingContext2D. The save () to store the current state of the Canvas. CanvasRenderingContext2D. Restore () restoring the Canvas to the last stored state. CanvasRenderingContext2D. Canvas reverse to identify the current context from which HTMLCanvasElement.
Other methods
Some other less common API methods.
CanvasRenderingContext2D. DrawFocusIfNeeded () if the given element is focused, the method in the current path is drawn around the focus ring. CanvasRenderingContext2D. ScrollPathIntoView () to the current path or scroll to view a given path.
drawImage()
The combination of Canvas and Web is the most frequently used method, which is generally used for image related processing, such as image compression, watermark synthesis and so on
grammar
context.drawImage(image, dx, dy);
context.drawImage(image, dx, dy, dWidth, dHeight);
context.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
Copy the code
Parameters that
The image, sx, and image elements are drawn on the starting abscissa of the Canvas. Sy, the initial ordinate of the image element drawn on the Canvas is sWidth, the length of the image itself drawn on the Canvas is sHeight, the height of the image itself drawn on the Canvas is dx, the abscissa of the upper left corner is dy, the ordinate of the upper left corner is dWidth, Width of the drawing image container area dHeight Height of the drawing image container areaCopy the code
The sample
const canvas = document.querySelector("#canvas");
let [width, height] = [window.innerWidth, window.innerHeight];
canvas.width = width;
canvas.height = height;
const img = new Image();
img.src = "./images/dog.jpg";
img.onload = function () {
let cxt = canvas.getContext("2d");
// cxt.drawImage(img, 0, 0);
// cxt.drawImage(img, 0, 0, 50, 50);
cxt.drawImage(img, 0.0.100.100.0.0.250.250);
};
Copy the code
createImageData
Method to create a new, empty ImageData object. All pixel information in this object is transparent black.
grammar
context.createImageData(width, height);
context.createImageData(imagedata);
Copy the code
Parameters that
width NumberThe width value contained in the ImageData object. If the ImageData object is converted to an image, this width is also the width of the final image rendering. heightNumberThe height value contained by the ImageData object. If the ImageData object is converted to an image, this height is also the height of the final image rendering. ImagedataObject An existing ImageData object. Only the width and height values of the ImageData object are used. All the pixel information contained in the ImageData object is converted to transparent black.Copy the code
The data values in the ImageData generated by the ::: prompt are an array of four values that make up a single pixel value :::Copy the code
putImageData
Draws the data from a given ImageData object onto a position graph. If a dirty rectangle is provided, only the pixels of that rectangle are drawn. This method is not affected by the canvas transformation matrix.
grammar
context.putImageData(imagedata, dx, dy);
context.putImageData(imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);
Copy the code
parameter
Imagedata dx is drawn on the Canvas at the starting abscissa. Dy, drawn on the Canvas starting ordinate dirtyX, the upper-left horizontal coordinate of the image data rendering area. The default value is0DirtyY, the ordinate of the upper-left corner of the image data rendering area. The default value is0. DirtyWidth, width of the image data rendering area dirtyHeight, height of the image data rendering areaCopy the code
getImageData
Return an ImageData object containing partial or complete pixel information for the Canvas.
grammar
context.getImageData(sx, sy, sWidth, sHeight);
Copy the code
parameter
sx NumberThe starting abscissa of the area of image data to be returned. syNumberThe starting ordinate of the area of image data to be returned. sWidthNumberThe width of the area of image data to be returned. sHeightNumberThe height of the area of image data to be returned.Copy the code
HTMLCanvasElement.toBlob()
grammar
void canvas.toBlob(callback, mimeType, quality);
Copy the code
parameter
callback FunctionA callback method to the successful execution of the toBlob() method, which supports a single argument representing the currently transformed Blob object. MimeType (optional)StringMimeType Indicates the mimeType of the image to be converted. The default value is image/ PNG, but it can also be image/ JPEG, or even image/webp (if the browser supports it). Quality (optional)NumberQuality indicates the image quality of the transformation. The range is0to1. Since Canvas's toBlob() method is lossless to PNG, this parameter is not valid by default unless the image mimeType is image/ JPEG or image/webp, in which case the default compression value is0.92.Copy the code
The sample
canvas.toBlob(function (blob) {
const a = document.createElement("a");
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "Image";
a.click();
window.URL.revokeObjectURL(url);
});
Copy the code
HTMLCanvasElement.toDataURL()
Canvas is essentially a bitmap image, as a result, the browser provides several API Canvas images can be converted into the data presented can be used as IMG, one of the most established method is HTMLCanvasElement. ToDataURL (), This method returns the data URI of the Canvas image, which is usually referred to as the Base64 address.
grammar
canvas.toDataURL(mimeType, quality);
Copy the code
parameter
MimeType (optional)StringMimeType Indicates the mimeType of the image to be converted. The default value is image/ PNG, but it can also be image/ JPEG, or even image/webp (if the browser supports it). Quality (optional)NumberQuality indicates the image quality of the transformation. The range is0to1. For this parameter to be valid, the mimeType of the image must be image/ JPEG or Image /webp. Any other mimeType value is invalid. The default compression quality is0.92. Depending on your eyes, if you compress an image using the quality parameter of toDataURL(), the same percentage of compression will render less well than Adobe PhotoshopCopy the code
case
Draw pictures
const canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = "images/dog.jpg";
img.onload = function () {
const { width, height } = img;
ctx.drawImage(img, 0.0);
const imgDt = ctx.getImageData(0.0, width, height);
// Modify the pixel
const data = imgDt.data;
for (let i = 0; i < data.length; i += 4) {
if (i < 100000 || i > 200000) {
data[i] = 0;
}
}
ctx.putImageData(imgDt, 0, height);
};
Copy the code
Pictures put ashes
/ * *@type {HTMLCanvasElement} * /
img.onload = function () {
const { width, height } = img;
ctx.drawImage(img, 0.0);
const imgDt = ctx.getImageData(0.0, width, height);
const data = imgDt.data;
for (let i = 0; i < data.length; i += 4) {
const [r, g, b] = [data[i], data[i + 1], data[i + 2]].const lm = 0.299 * r + 0.587 * g + 0.114 * b;
data[i] = lm;
data[i + 1] = lm;
data[i + 2] = lm;
}
ctx.putImageData(imgDt, 800.0);
};
Copy the code
Mosaic picture
img.onload = function () {
const { width, height } = img;
ctx.drawImage(img, 0.0);
const imgDt = ctx.getImageData(0.0, width, height);
const data = imgDt.data;
for (let y = 0; y < height; y += 20) {
for (let x = 0; x < width; x += 20) {
let ind = (y * width + x) * 4;
const [r, g, b] = [data[ind], data[ind + 1], data[ind + 2]];
ctx.fillStyle = `rgb(${r}.${g}.${b}) `; ctx.fillRect(x, y, size, size); }}};Copy the code