Canvas API

Overview

The <canvas> element is used to generate images. It itself is like a canvas, and JavaScript generates images on it by operating its API. Its bottom layer is a pixel, basically <canvas> is a bitmap that can be manipulated with JavaScript.

The difference between it and SVG images is that <canvas> is a script that calls various methods to generate images, while SVG is an XML file that generates images through various sub-elements.

Before using the Canvas API, you need to create a new <canvas> element in the web page.

<canvas id="myCanvas" width="400" height="250">
  Your browser does not support Canvas
</canvas>

If the browser does not support this API, the text in the middle of the <canvas> tag will be displayed: "Your browser does not support Canvas".

Each <canvas> element has a corresponding CanvasRenderingContext2D object (context object). The Canvas API is defined on this object.

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

In the above code, the getContext() method of the <canvas> element node object returns the CanvasRenderingContext2D object.

Note that the Canvas API requires the getContext method to specify the parameter 2d, which means that the <canvas> node generates a 2D plane image. If the parameter is webgl, it means that it is used to generate 3D three-dimensional patterns, and this part belongs to the WebGL API.

According to usage, Canvas API is divided into two parts: drawing graphics and image processing.

Canvas API: Drawing graphics

Canvas provides a flat space for drawing, and each point in the space has its own coordinates. The origin (0, 0) is at the upper left corner of the image, the positive direction of the x axis is the origin to the right, and the positive direction of the y axis is the origin down.

Path

The following methods and properties are used to draw the path.

-CanvasRenderingContext2D.beginPath(): start drawing the path. -CanvasRenderingContext2D.closePath(): End the path, return to the starting point of the current path, and draw a straight line from the current point to the starting point. If the graph is closed, or there is only one point, then this method will not produce any effect. -CanvasRenderingContext2D.moveTo(): Set the starting point of the path, that is, move the starting point of a new path to the (x,y) coordinates. -CanvasRenderingContext2D.lineTo(): Use a straight line to connect from the current point to the (x, y) coordinates. -CanvasRenderingContext2D.fill(): Fill color inside the path (default is black). -CanvasRenderingContext2D.stroke(): coloring of path lines (default is black). -CanvasRenderingContext2D.fillStyle: Specify the color and style of the path fill (the default is black). -CanvasRenderingContext2D.strokeStyle: Specify the color and style of the path line (the default is black).

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

ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.lineTo(100, 200);

The above code only determines the shape of the path, and it is not visible on the canvas because there is no color. So it needs to be colored.

ctx.fill();
// or
ctx.stroke();

In the above code, these two methods can make the path visible. fill() fills the color inside the path to make it a solid shape; stroke() only colors the path lines.

Both methods use black by default, and you can use the fillStyle and strokeStyle properties to specify other colors.

ctx.fillStyle = "red";
ctx.fill();
// or
ctx.strokeStyle = "red";
ctx.stroke();

The above code specifies the color of the fill and line as red.

Line type

The following methods and attributes control the visual characteristics of the line.

-CanvasRenderingContext2D.lineWidth: Specify the width of the line, the default is 1.0. -CanvasRenderingContext2D.lineCap: Specify the style of the end of the line. There are three possible values: butt (default value, the end is a rectangle), round (the end is a circle), and square (the end is a protruding rectangle , The width of the rectangle remains unchanged, and the height is half the width of the line). -CanvasRenderingContext2D.lineJoin: Specify the style of the intersection of line segments. There are three possible values: round (the intersection is a fan), bevel (the intersection is the base of the triangle), and miter (the default value, the intersection is a diamond) . -CanvasRenderingContext2D.miterLimit: Specify the length of the intersection diamond, the default is 10. This property is only valid when the value of the lineJoin property is equal to miter. -CanvasRenderingContext2D.getLineDash(): returns an array representing the length of the line segments and spacing in the dashed line. -CanvasRenderingContext2D.setLineDash(): array, used to specify the length of the line segment and spacing in the dashed line.

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

ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.lineTo(100, 200);

ctx.lineWidth = 3;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.setLineDash([15, 5]);
ctx.stroke();

In the above code, the width of the line is 3, and the ends and intersections of the lines are changed to rounded corners and set to dashed lines.

Rectangle

The following method is used to draw a rectangle.

-CanvasRenderingContext2D.rect(): draw a rectangular path. -CanvasRenderingContext2D.fillRect(): Fill a rectangle. -CanvasRenderingContext2D.strokeRect(): draw a rectangular border. -CanvasRenderingContext2D.clearRect(): The pixels in the specified rectangular area become transparent.

The formats of the above four methods are the same, and all accept four parameters, which are the abscissa and ordinate of the upper left corner of the rectangle, and the width and height of the rectangle.

The CanvasRenderingContext2D.rect() method is used to draw a rectangular path.

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

ctx.rect(10, 10, 100, 100);
ctx.fill();

The above code draws a square, the upper left corner coordinates are (10, 10), the width and height are both 100.

CanvasRenderingContext2D.fillRect() is used to fill a rectangular area with color.

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

ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);

The above code draws a green square, the upper left corner coordinates are (10, 10), width and height are both 100.

CanvasRenderingContext2D.strokeRect() is used to draw the border of a rectangular area.

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

ctx.strokeStyle = "green";
ctx.strokeRect(10, 10, 100, 100);

The above code draws a green hollow square, the upper left corner coordinates are (10, 10), width and height are both 100.

CanvasRenderingContext2D.clearRect() is used to erase the pixel color of the specified rectangular area, which is equivalent to removing all the previous drawing effects.

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

ctx.fillRect(10, 10, 100, 100);
ctx.clearRect(15, 15, 90, 90);

The above code first draws a 100 x 100 square, and then erases a 90 x 90 area inside it, which is equivalent to forming a border with a width of 5 pixels.

Arc

The following methods are used to draw arcs.

-CanvasRenderingContext2D.arc(): draw an arc by specifying the center and radius. -CanvasRenderingContext2D.arcTo(): Draw an arc by specifying two tangents and a radius.

CanvasRenderingContext2D.arc() is mainly used to draw circles or sectors.

// format
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);

// instance
ctx.arc(5, 5, 5, 0, 2 * Math.PI, true);

The x and y parameters of the arc() method are the coordinates of the center of the circle, radius is the radius, and startAngle and endAngle are the starting and ending angles of the sector (in radians), anticlockwise Indicates whether the drawing should be drawn counterclockwise (true) or clockwise (false). This parameter is used to control the direction of the sector (for example, upper semicircle or lower semicircle).

The following is an example of drawing a solid circle.

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

ctx.beginPath();
ctx.arc(60, 60, 50, 0, Math.PI * 2, true);
ctx.fill();

The above code draws a complete circle with a radius of 50, a starting angle of 0, and an ending angle of 2 * PI.

An example of drawing a hollow semicircle.

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

ctx.beginPath();
ctx.moveTo(50, 20);
ctx.arc(100, 20, 50, 0, Math.PI, false);
ctx.stroke();

The CanvasRenderingContext2D.arcTo() method is mainly used to draw an arc. The coordinates of two points need to be given. The current point and the first point form a straight line, and the first point and the second point form another straight line. Then Draw arcs that are tangent to these two lines.

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

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arcTo(50, 50, 100, 0, 25);
ctx.lineTo(100, 0);
ctx.stroke();

In the above code, arcTo() has 5 parameters, the first two parameters are the coordinates of the first point, the third and fourth parameters are the coordinates of the second point, and the fifth parameter is the radius. Then, (0, 0) and (50, 50) form a straight line, and then (50, 50) and (100, 0) form a second straight line. The arc is the part that is tangent to these two straight lines.

Text

The following methods and properties are used to draw text.

-CanvasRenderingContext2D.fillText(): draw a solid character at the specified position. -CanvasRenderingContext2D.strokeText(): draw a hollow character at the specified position. -CanvasRenderingContext2D.measureText(): returns a TextMetrics object. -CanvasRenderingContext2D.font: Specify font size and font, the default value is 10px sans-serif. -CanvasRenderingContext2D.textAlign: The alignment of the text, the default value is start. -CanvasRenderingContext2D.direction: The direction of the text, the default value is inherit. -CanvasRenderingContext2D.textBaseline: The vertical position of the text, the default value is alphabetic.

The fillText() method is used to draw solid characters at the specified position.

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

The method accepts four parameters.

-text: The string to be filled. -x: The abscissa of the starting point of the text, in pixels. -y: The ordinate of the starting point of the text, in pixels. -maxWidth: The maximum pixel width of the text. This parameter is optional. If omitted, it means that there is no limit to the width. If the actual length of the text exceeds the value specified by this parameter, the browser will try to fill it with a smaller font.

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

ctx.fillText("Hello world", 50, 50);

The above code writes the string Hello world at the position of (50, 50).

Note that the fillText() method does not support text line breaks, and all text must appear on one line. If you want to generate multiple lines of text, you only have to call the fillText() method multiple times.

The strokeText() method is used to add hollow characters, and its parameters are the same as fillText().

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

ctx.strokeText("Hello world", 50, 50);

The text drawn by the above two methods is the default size of 10px, sans-serif font, and the font setting can be changed by the font property. The value of this property is a string, just use the CSS font property.

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

ctx.font = "Bold 20px Arial";
ctx.fillText("Hello world", 50, 50);

The textAlign property is used to specify the alignment of the text. It can take the following values.

-left: align left -right: align right -center: centered -start: The default value, the starting point is aligned (left-to-right text is left-aligned, and right-to-left text is right-aligned). -end: End alignment (left-to-right text is right-aligned, right-to-left text is left-aligned).

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

ctx.font = "Bold 20px Arial";
ctx.textAlign = "center";
ctx.fillText("Hello world", 50, 50);

The direction attribute specifies the direction of the text. The default value is inherit, which means to inherit the settings of <canvas> or document. Other values ​​include ltr (from left to right) and rtl (from right to left).

The textBaseline attribute specifies the vertical position of the text and can take the following values.

-top: Align the upper part (the baseline of the letter is moved up as a whole). -hanging: Hanging alignment (the upper edge of the letter is on a straight line), suitable for Indian and Tibetan. -middle: Align the middle (the center line of the letter is on a straight line). -alphabetic: The default value, which means that the letter is located in the normal position of the alphabet (the third line of the four-line grid). -ideographic: Align the bottom edge (the bottom edge of the letter is on a straight line), used in East Asian text. -bottom: Align the bottom (the baseline of the letter moves down). For English letters, this setting is no different from ideographic.

The measureText() method accepts a string as a parameter and returns a TextMetrics object from which the information of the parameter string can be obtained. Currently, it is mainly the width of the text after rendering (width).

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

var text1 = ctx.measureText("Hello world");
text1.width; // 49.46

ctx.font = "Bold 20px Arial";
var text2 = ctx.measureText("Hello world");
text2.width; // 107.78

In the above code, the string Hello world with the size of 10px will have a width of 49.46 after rendering. After zooming in to 20px, the width is 107.78.

Gradient color and image fill

The following methods are used to set gradient effects and image fill effects.

-CanvasRenderingContext2D.createLinearGradient(): define the linear gradient style. -CanvasRenderingContext2D.createRadialGradient(): define the radial gradient style. -CanvasRenderingContext2D.createPattern(): Define the image filling style.

The createLinearGradient() method generates a linear gradient style according to a given straight line.

ctx.createLinearGradient(x0, y0, x1, y1);

The ctx.createLinearGradient(x0, y0, x1, y1) method accepts four parameters: x0 and y0 are the abscissa and ordinate of the starting point, and x1 and y1 are the abscissa and ordinate of the end point coordinate. Through different coordinate values, you can generate a gradient from top to bottom, from left to right, and so on.

The return value of this method is a CanvasGradient object, which has only one addColorStop() direction, which is used to specify the color of the gradient point. The addColorStop() method accepts two parameters, the first parameter is a position between 0 and 1, 0 means the start point, 1 means the end point, and the second parameter is a string representing the CSS color.

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

var gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "green");
gradient.addColorStop(1, "white");
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);

In the above code, after defining the gradient style gradient, assign this style to the fillStyle property, and then fillRect() will generate a rectangular area filled with this style.

The createRadialGradient() method defines a radiative gradient, which requires two circles to be specified.

ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);

The createRadialGradient() method accepts six parameters, x0 and y0 are the coordinates of the center of the circle where the radiation starts, r0 is the radius of the start circle, and x1 and y1 are the circles where the radiation ends. The center coordinate of the circle, r1 is the radius of the ending circle.

The return value of this method is also a CanvasGradient object.

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

var gradient = ctx.createRadialGradient(100, 100, 50, 100, 100, 100);
gradient.addColorStop(0, "white");
gradient.addColorStop(1, "green");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 200);

In the above code, after generating the radiation pattern, fill a rectangle with this pattern.

The createPattern() method defines an image filling style, repeating the image in the specified direction and filling the specified area.

ctx.createPattern(image, repetition);

This method accepts two parameters. The first parameter is the image data, which can be a <img> element, another <canvas> element, or a Blob object representing an image. The second parameter is a string with four possible values, namely repeat (two-way repeat), repeat-x (horizontal repeat), repeat-y (vertical repeat), and no-repeat (not repeated). If the second parameter is an empty string or null, it is equivalent to null.

The return value of this method is a CanvasPattern object.

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

var img = new Image();
img.src = "https://example.com/pattern.png";
img.onload = function () {
  var pattern = ctx.createPattern(img, "repeat");
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, 400, 400);
};

In the above code, after the image is loaded successfully, use createPattern() to generate the image style, and then use this style to fill the specified area.

Shadow

The following properties are used to set the shadow.

-CanvasRenderingContext2D.shadowBlur: The blur degree of the shadow, the default is 0. -CanvasRenderingContext2D.shadowColor: The color of the shadow, the default is black. -CanvasRenderingContext2D.shadowOffsetX: The horizontal offset of the shadow, the default is 0. -CanvasRenderingContext2D.shadowOffsetY: the vertical displacement of the shadow, the default is 0.

Below is an example.

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

ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.shadowBlur = 5;
ctx.shadowColor = "rgba(0,0,0,0.5)";

ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);

Canvas API: Image Processing

CanvasRenderingContext2D.drawImage()

The Canvas API allows you to write image files to the canvas. After reading the image, use the drawImage() method to put the image on the canvas.

CanvasRenderingContext2D.drawImage() has three usage formats.

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

The meaning of each parameter is as follows.

-image: image element -sx: The abscissa inside the image, used to map to the placement point on the canvas. -sy: The ordinate inside the image, used to map to the placement point on the canvas. -sWidth: The width of the image on the canvas, which will produce a zoom effect. If not specified, the image will not be scaled and will occupy the width of the canvas according to its actual size. -sHeight: The height of the image on the canvas, which will produce a zoom effect. If not specified, the image will not be scaled and will occupy the height of the canvas according to its actual size. -dx: The abscissa inside the canvas, used to place the upper left corner of the image -dy: the ordinate inside the canvas, used to place the upper right corner of the image -dWidth: The width of the image inside the canvas, which will produce a zoom effect. -dHeight: The height of the image inside the canvas, which will produce a zoom effect.

The following is the simplest usage scenario. Place the image on the canvas and align the upper left corner of the two.

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

var img = new Image();
img.src = "image.png";
img.onload = function () {
  ctx.drawImage(img, 0, 0);
};

The above code puts a PNG image on the canvas. At this time, the image will be the original size. If the canvas is smaller than the image, only the upper left corner of the image will be displayed, which is exactly equal to the size of the canvas.

If you want to display a complete picture, you can use the width and height of the image to set the width and height of the canvas.

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

var image = new Image(60, 45);
image.onload = drawImageActualSize;
image.src = "https://example.com/image.jpg";

function drawImageActualSize() {
  canvas.width = this.naturalWidth;
  canvas.height = this.naturalHeight;
  ctx.drawImage(this, 0, 0, this.naturalWidth, this.naturalHeight);
}

In the above code, the size of the <canvas> element is set to the original size of the image to ensure the complete display of the image. Due to the original size of the image, it can only be obtained after the image is successfully loaded. Therefore, to adjust the size of the canvas, it must be placed in the listener function image.onload.

Pixel read and write

The following three methods are related to pixel reading and writing.

-CanvasRenderingContext2D.getImageData(): read the canvas into an ImageData object -CanvasRenderingContext2D.putImageData(): Write the ImageData object to the canvas -CanvasRenderingContext2D.createImageData(): Generate ImageData object

(1) getImageData()

The CanvasRenderingContext2D.getImageData() method is used to read the content of <canvas> and return an ImageData object containing the information of each pixel.

ctx.getImageData(sx, sy, sw, sh);

The getImageData() method accepts four parameters. sx and sy are the coordinates of the upper left corner of the reading area, and sw and sh are the width and height of the reading area. If you want to read the entire <canvas> area, you can write it as follows.

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

var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

The getImageData() method returns an ImageData object. The object has three properties.

-ImageData.data: A one-dimensional array. The value of the array is the red, green, blue, and alpha channel values ​​of each pixel in turn (each value ranges from 0 to 255), so the length of the array is equal to image pixel width x image pixel height x 4 . This array is not only readable, but also writable, so by operating this array, you can achieve the purpose of manipulating images. -ImageData.width: Floating point number, representing the pixel width of ImageData. -ImageData.height: Floating point number, representing the pixel height of ImageData.

(2) putImageData()

The CanvasRenderingContext2D.putImageData() method draws the pixels of the ImageData object on the <canvas> canvas. There are two usage formats for this method.

ctx.putImageData(imagedata, dx, dy);
ctx.putImageData(imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);

The method has the following parameters.

-imagedata: ImageData object containing pixel information. -dx: The abscissa inside the <canvas> element, used to place the upper left corner of the ImageData image. -dy: The ordinate inside the <canvas> element, used to place the upper left corner of the ImageData image. -dirtyX: The abscissa of the ImageData image, used as the abscissa of the upper left corner of the rectangular area placed in <canvas>, the default is 0. -dirtyY: The ordinate inside the ImageData image, used as the ordinate of the upper left corner of the rectangular area placed in <canvas>, the default is 0. -dirtyWidth: the width of the rectangular area placed in <canvas>, the default is the width of the ImageData image. -dirtyHeight: the height of the rectangular area placed in <canvas>, the default is the height of the ImageData image.

The following is an example of drawing an ImageData object to <canvas>.

ctx.putImageData(imageData, 0, 0);

(3) createImageData()

The CanvasRenderingContext2D.createImageData() method is used to generate an empty ImageData object, all pixels are transparent and black (that is, each value is 0). There are two usage formats for this method.

ctx.createImageData(width, height);
ctx.createImageData(imagedata);

The parameters of the createImageData() method are as follows.

-width: The width of the ImageData object, in pixels. -height: The height of the ImageData object, in pixels. -imagedata: an existing ImageData object, the return value will be a copy of this object.

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

var imageData = ctx.createImageData(100, 100);

In the above code, imageData is a 100 x 100 pixel area, where each pixel is transparent and black.

CanvasRenderingContext2D.save(), CanvasRenderingContext2D.restore()

The CanvasRenderingContext2D.save() method is used to save the current style of the canvas to the stack, which is equivalent to generating a style snapshot in memory.

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

ctx.save();

In the above code, save() will generate a snapshot of the default style of the canvas.

The CanvasRenderingContext2D.restore() method restores the style of the canvas to the last saved snapshot. If there is no saved snapshot, no effect will be produced.

Context, the restore method is used to restore to the last saved context.

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

ctx.save();

ctx.fillStyle = "green";
ctx.restore();

ctx.fillRect(10, 10, 100, 100);

The above code draws a rectangle. The fill color of the rectangle was originally set to green, but the restore() method undoes this setting and restores the style to the last saved state (ie the default style), so the actual fill color is black (the default color).

CanvasRenderingContext2D.canvas

The CanvasRenderingContext2D.canvas property points to the <canvas> element where the current CanvasRenderingContext2D object is located. This attribute is read-only.

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

ctx.canvas === canvas; // true

Image transformation

The following method is used for image transformation.

-CanvasRenderingContext2D.rotate(): image rotation -CanvasRenderingContext2D.scale(): image scaling -CanvasRenderingContext2D.translate(): image translation -CanvasRenderingContext2D.transform(): complete image transformation through a transformation matrix -CanvasRenderingContext2D.setTransform(): cancel the previous image transformation

(1) rotate()

The CanvasRenderingContext2D.rotate() method is used for image rotation. It accepts a radian value as a parameter, which represents the degree of clockwise rotation.

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

ctx.rotate((45 * Math.PI) / 180);
ctx.fillRect(70, 0, 100, 30);

The above code will display a rectangle tilted 45 degrees clockwise. Note that the rotate() method must be called before the fillRect() method, otherwise it will not work.

The center of rotation is always the origin of the upper left corner of the canvas. If you want to change the center point, you need to use the translate() method to move the canvas.

(2)scale()

The CanvasRenderingContext2D.scale() method is used to scale the image. It accepts two parameters, the scaling factor in the direction of the x axis and the scaling factor in the direction of the y axis. By default, a unit is a pixel, and the zoom factor can zoom the unit. For example, the zoom factor 0.5 means to reduce the size to 50% of the original size, and the zoom factor 10 means to zoom in ten times.

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

ctx.scale(10, 3);
ctx.fillRect(10, 10, 10, 10);

In the above code, the original rectangle is 10 x 10, and it is shown as 100 x 30 after scaling.

If the zoom factor is 1, it means that the image does not have any zoom. If it is -1, it means the direction is reversed. ctx.scale(-1, 1) means horizontal flip, ctx.scale(1, -1) means vertical flip.

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

ctx.scale(1, -2);
ctx.font = "16px serif";
ctx.fillText("Hello world!", 20, -20);

The above code will display a horizontally inverted Hello World! with a height magnification of 2 times.

Note that the essence of negative zoom is coordinate flip, and the coordinate axis for which is the coordinate axis of the origin of the upper left corner of the canvas.

(3) translate()

The CanvasRenderingContext2D.translate() method is used to translate the image. It accepts two parameters, which are the distance (in pixels) of the x-axis and y-axis movement.

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

ctx.translate(50, 50);
ctx.fillRect(0, 0, 100, 100);

(4) transform()

The CanvasRenderingContext2D.transform() method accepts six elements of a transformation matrix as parameters to complete the transformations such as scaling, rotation, movement and tilt.

Its usage format is as follows.

ctx.transform(a, b, c, d, e, f);
/*
a: Horizontal zoom (default value 1, unit multiple)
b: horizontal tilt (default value 0, unit radian)
c: vertical tilt (default value 0, unit radian)
d: Vertical zoom (default value 1, unit multiple)
e: horizontal displacement (default value 0, unit pixel)
f: vertical displacement (default value 0, unit pixel)
*/

Below is an example.

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

ctx.transform(2, 0, 0, 1, 50, 50);
ctx.fillRect(0, 0, 100, 100);

In the above code, the original graphic is a 100 x 100 rectangle, the result is scaled to a 200 x 100 rectangle, and the upper left corner is moved from (0, 0) to (50, 50).

Note that multiple transform() methods have superimposing effects.

(5) setTransform()

The CanvasRenderingContext2D.setTransform() method cancels the previous graphics transformation and restores the canvas to the state specified by this method. The parameters of this method are exactly the same as the transform() method.

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

ctx.translate(50, 50);
ctx.fillRect(0, 0, 100, 100);

ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.fillRect(0, 0, 100, 100);

In the above code, the upper left corner of the rectangle drawn by the first fillRect() method is translated from (0, 0) to (50, 50). The setTransform() method cancels this transformation (the drawn graphics are not affected), and restores the canvas to the default state (transform rectangle 1, 0, 0, 1, 0, 0), so the second rectangle Return to (0, 0) in the upper left corner.

<canvas> Element method

In addition to the methods provided by the CanvasRenderingContext2D object, the <canvas> element itself also has its own methods.

HTMLCanvasElement.toDataURL()

The toDataURL() method of the <canvas> element can convert Canvas data into an image in Data URI format.

canvas.toDataURL(type, quality);

The toDataURL() method accepts two parameters.

-type: A string that indicates the format of the image. The default is image/png, another available value is image/jpeg, Chrome browser can also use image/webp. -quality: floating point number, between 0 and 1, which represents the quality coefficient of JPEG and WebP images, the default value is 0.92.

The return value of this method is a string in Data URI format.

function convertCanvasToImage(canvas) {
  var image = new Image();
  image.src = canvas.toDataURL("image/png");
  return image;
}

The above code transforms the <canvas> element into a PNG Data URI.

var fullQuality = canvas.toDataURL("image/jpeg", 0.9);
var mediumQuality = canvas.toDataURL("image/jpeg", 0.6);
var lowQuality = canvas.toDataURL("image/jpeg", 0.3);

The above code converts the <canvas> element into three JPEG images of high quality, medium quality, and low quality.

HTMLCanvasElement.toBlob()

The HTMLCanvasElement.toBlob() method is used to convert the <canvas> image into a Blob object, the default type is image/png. Its usage format is as follows.

// format
canvas.toBlob(callback, mimeType, quality)

// example
canvas.toBlob(function (blob) {...},'image/jpeg', 0.95)

The toBlob() method can accept three parameters.

-callback: callback function. It accepts the generated Blob object as a parameter. -mimeType: string, the MIMEType of the image, the default is image/png. -quality: floating-point number, between 0 and 1, indicating the quality of the image, only valid for images of image/jpeg and image/webp types.

Note that this method has no return value.

The following example copies <canvas> image into <img> image.

var canvas = document.getElementById("myCanvas");

function blobToImg(blob) {
  var newImg = document.createElement("img");
  var url = URL.createObjectURL(blob);

  newImg.onload = function () {
    // After using, release the URL object
    URL.revokeObjectURL(url);
  };

  newImg.src = url;
  document.body.appendChild(newImg);
}

canvas.toBlob(blobToImg);

Canvas usage examples

Animation effects

By changing the coordinates, it is easy to produce animation effects on the Canvas element.

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

var posX = 20;
var posY = 100;

setInterval(function () {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  posX += 1;
  posY += 0.25;

  ctx.beginPath();
  ctx.fillStyle = "white";

  ctx.arc(posX, posY, 10, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.fill();
}, 30);

The above code will produce a small dot that moves to the bottom right every 30 milliseconds. At the beginning of the setInterval() function, the reason for re-rendering the canvas with black background color is to erase the dots from the previous step.

On the basis of this example, various motion trajectories can be generated by setting the coordinates of the center of the circle. The following is an example of first rising and then falling.

var vx = 10;
var vy = -10;
var gravity = 1;

setInterval(function () {
  posX += vx;
  posY += vy;
  vy += gravity;
  // ...
});

In the above code, the x coordinate always increases, which means continuous rightward movement. The y coordinate first becomes smaller, and then increases continuously under the action of gravity, indicating that it first rises and then falls.

Pixel processing

Through the getImageData() method and the putImageData() method, each pixel can be processed, and then the image content can be manipulated, so the image can be rewritten.

The following is a general wording of image processing.

if (canvas.width > 0 && canvas.height > 0) {
  var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  filter(imageData);
  context.putImageData(imageData, 0, 0);
}

In the above code, filter is a function for processing pixels. The following are several common filters.

(1) Grayscale effect

Grayscale is the arithmetic average of the three pixel values ​​of red, green, and blue, which actually converts the image into a black and white form.

grayscale = function (pixels) {
  var d = pixels.data;
  for (var i = 0; i < d.length; i += 4) {
    var r = d[i];
    var g = d[i + 1];
    var b = d[i + 2];
    d[i] = d[i + 1] = d[i + 2] = (r + g + b) / 3;
  }
  return pixels;
};

In the above code, d[i] is the red value, d[i+1] is the green value, d[i+2] is the blue value, and d[i+3] is the alpha channel value. The algorithm for converting to grayscale is to add the three values ​​of red, green, and blue and divide by 3, and then write the result back to the array.

(2) Retro effect

The retro effect (sepia) is to take the three values ​​of red, green, and blue, respectively, to take a certain weighted average of these three values, so that the image has an ancient effect.

sepia = function (pixels) {
  var d = pixels.data;
  for (var i = 0; i < d.length; i += 4) {
    var r = d[i];
    var g = d[i + 1];
    var b = d[i + 2];
    d[i] = r * 0.393 + g * 0.769 + b * 0.189; // red
    d[i + 1] = r * 0.349 + g * 0.686 + b * 0.168; // green
    d[i + 2] = r * 0.272 + g * 0.534 + b * 0.131; // blue
  }
  return pixels;
};

(3) Red mask effect

The red mask refers to making the image appear reddish. The algorithm is to set the red channel to the average of the three values ​​of red, green, and blue, and set both the green channel and the blue channel to 0.

var red = function (pixels) {
  var d = pixels.data;
  for (var i = 0; i < d.length; i += 4) {
    var r = d[i];
    var g = d[i + 1];
    var b = d[i + 2];
    d[i] = (r + g + b) / 3; // take the average of the red channel
    d[i + 1] = d[i + 2] = 0; // Both the green channel and the blue channel are set to 0
  }
  return pixels;
};

(4) Brightness effect

The brightness effect (brightness) refers to making the image brighter or darker. The algorithm adds a positive or negative value to the red channel, green channel, and blue channel at the same time.

var brightness = function (pixels, delta) {
  var d = pixels.data;
  for (var i = 0; i < d.length; i += 4) {
    d[i] += delta; // red
    d[i + 1] += delta; // green
    d[i + 2] += delta; // blue
  }
  return pixels;
};

(5) Reversal effect

The invert effect (invert) refers to the effect that the picture presents a color inversion. The algorithm is that the red, green, and blue channels all take their opposite values ​​(255-original value).

invert = function (pixels) {
  var d = pixels.data;
  for (var i = 0; i < d.length; i += 4) {
    d[i] = 255 - d[i];
    d[i + 1] = 255 - d[i + 1];
    d[i + 2] = 255 - d[i + 2];
  }
  return pixels;
};