From simple basic graphics to complex, cool animations, the 2D graphics rendering context obtained through the canvas element CanvasRenderingContext2D
enables graphical drawing using a rich API. This article summarizes the APIs for all the rendering contexts used in previous canvas tutorials.
You can refer to the previous tutorials:
- How to draw basic graphics can be consulted: Canvas basic graphics drawing
- How to move the rotation scale for basic graphics can be consulted: Canvas graphics transformations
- How to set basic graphic colors and styles can be consulted: canvas styles and colors
- How to use external pictures and graphic combinations can be consulted: canvas using pictures, graphic combinations and cropping
- Canvas how to save and load images can be consulted: Canvas image preservation
- Canvas animation Tutorials and Examples:
- Canvas Series Tutorials can be consulted: canvas
The methods and properties described below are the CanvasRenderingContext2D
methods and properties of the object. The method is called as follows:
var=document.getElementById("canvas");var=canvas.getContext("2d");// 使用ctx即可调用ctx.fillStyle="rgba(0, 0, 200, 0.5)";ctx.fillRect (30,30,55,50);
More detailed interface API documentation can be found in the official documentation.
Basic graphic Drawing
Used to draw basic graphics. Refer to this article for more detailed usage: Canvas basic drawing
Rectangle Drawing (no path required)
void ctx.fillRect(x, y, width, height);
- Draws a filled rectangle with the beginning of the rectangle at (x, y), and the size of the rectangle is width and height
void ctx.strokeRect(x, y, width, height);
- In canvas, use the current drawing style to draw a rectangle with a starting point in (x, y), W width, h for height
void ctx.clearRect(x, y, width, height);
- Sets the specified rectangular area (at points (x, y) as the starting point, the range is (width, height)) all pixels become transparent and erases everything drawn before
The above API parameters are described below:
x
X-coordinate of the starting point of the rectangle (upper-left point)
y
Y-coordinate of the starting point of the rectangle
width
Width of Rectangle
height
Height of the rectangle
Draw text
void ctx.fillText(text, x, y [, maxWidth]);
- Draw (fill) text at (x, y) position
void ctx.strokeText(text, x, y [, maxWidth]);
- Draw (stroke) text at (x, y) position
ctx.measureText(text);
- Returns a Textmetrics object that contains information about the size of the text (such as the width of the text)
The above API parameters are described below:
x
X-coordinate of the beginning of text
y
The y-coordinate of the beginning of the text
text
Text that needs to be drawn
maxWidth
Optional, maximum width to draw
Path graphics
void ctx.beginPath();
- Start a new path by clearing the empty path list
void ctx.closePath();
- Returns the point of the pen to the starting point of the current sub-path. It attempts to draw a line from the current point to the starting point. If the graphic is already closed or has only one point, then this method does nothing
void ctx.moveTo(x, y);
- Moves the starting point of a new sub-path to (x, y) coordinates
void ctx.lineTo(x, y);
- Use a straight line to connect the last point of the subpath to the x, Y coordinates
void ctx.quadraticCurveTo(cpx, cpy, x, y);
- Add a 2-time Bezier curve path
cpx, cpy
First control point (x, y) coordinates
x,y
To end point coordinates
void ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
- Add a 3-time Bezier curve path. This method requires three points. The first, second point is the control point, and the third point is the end point. The starting point is the last point of the current path and can be modified by calling MoveTo () before the Bezier curve is drawn.
cp1x, cp1y
First control point (x, y) coordinates
cp2x, cp2y
Second control point (x, y) coordinates
x,y
End point coordinates
void ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
- Draws an ARC path, where the center of the ARC path is at (x, y), the radius is r, and the direction specified by anticlockwise (clockwise by default) is drawn from StartAngle to the end of the Endangle.
x,y
To draw the center coordinate of the circle on which the arc is located
radius
As Radius
startAngle
and endAngle
A parameter that defines the start and end radians for the x-axis as the base radian.
anticlockwise
As a Boolean value that specifies the draw reverse, the default is false to indicate a clockwise direction. True indicates a counterclockwise direction.
void ctx.arcTo(x1, y1, x2, y2, radius);
- Draws an ARC path based on the control point and radius, using the current stroke (the stop point for a function such as the previous MoveTo or LineTo). Draws an arc path between two tangents based on the line that the current stroke is connected to a given control point 1, and a line connected by Control point 1 to control point 2 as a tangent of a circle with a specified radius.
x1,y1
Specify the coordinates of the first control point
x2,y2
Specify the coordinates of the second control point
radius
Specify the radius of the arc
void ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
- Add an elliptical path, where the center of the ellipse is at (x, y), the radius is RadiusX and radiusy, in the direction specified by anticlockwise (the default clockwise), drawn from StartAngle, and ended with Endangle.
x,y
(x, y) coordinates of the ellipse center
radiusX
Radius of the elliptical long axis
radiusY
Radius of the elliptical short axis
rotation
The rotation angle of the ellipse, expressed in radians (non-angular degrees)
startAngle
The angle of the starting point to be drawn, measured from the x-axis, expressed in radians (non-angular degrees)
endAngle
The angle of the end point that the ellipse will be drawn in radians (non-angular degrees)
anticlockwise
As a Boolean value that specifies the draw reverse, the default is false to indicate a clockwise direction. True indicates a counterclockwise direction.
void ctx.rect(x, y, width, height);
- Creates a rectangular path, where the starting position of the rectangle is (x, y), and the dimensions are width and height
Path
void ctx.fill();
void ctx.fill(fillRule);
void ctx.fill(path, fillRule);
- Populate a subpath with the current style
path
The path that needs to be populated Path2D
fillRule
An algorithm that determines whether the point is within the path or outside the path: "Nonzero", "evenodd"
void ctx.stroke();
void ctx.stroke(path);
- Stroke sub-path using the current style
void ctx.clip();
void ctx.clip(fillRule);
void ctx.clip(path, fillRule);
- Creates a clipping path from the current path.
clip()
after the call, all the information drawn will only appear inside the clipping path
boolean ctx.isPointInPath(x, y);
boolean ctx.isPointInPath(x, y, fillRule);
boolean ctx.isPointInPath(path, x, y);
boolean ctx.isPointInPath(path, x, y, fillRule);
- Determine if the current path contains a detection point
boolean ctx.isPointInStroke(x, y);
boolean ctx.isPointInStroke(path, x, y);
- Determine if the detection point is on the stroke of the path
Colors and styles
Controls the color and style of drawing graphics. Refer to this article for more detailed usage: Canvas styles and colors
Linear
ctx.lineWidth = value;
- The width of the line. Default 1.0
ctx.lineCap = "butt" || "round" || "square";
- The type of the end of the line. Allowable values: Butt (default), round, square
ctx.lineJoin = "miter" || "round" || "bevel";
- Defines the type of inflection point at which two lines intersect. Allowable values: round, Bevel, miter (default)
ctx.miterLimit = value;
- The miter face limit scale. Default 10
Array ctx.getLineDash();
- Returns a set of numbers that describe the length of alternating line segments and spacing (coordinate space units). If the number of array elements is odd, the array elements are copied and duplicated. For example, setting the segment to [5, 15, 25] will get the following return values [5, 15, 25, 5, 15, 25].
void ctx.setLineDash(segments);
- Sets the current line segment style
ctx.lineDashOffset = value;
- Sets the dashed offset property, which is the number of float precision. The initial value is 0.0.
Text Style
ctx.font = value;
- Sets the properties of the current font style when drawing text
value
A domstring string that conforms to the CSS font syntax. The default font is 10px Sans-serif.
ctx.textAlign = "left" || "right" || "center" || "start" || "end";
ctx.textBaseline = "top" || "hanging" || "middle" || "alphabetic" || "ideographic" || "bottom";
- Baseline alignment Settings
ctx.direction = "ltr" || "rtl" || "inherit";
Fill and stroke styles
ctx.fillStyle = color || gradient || pattern
- The color and style inside the graphic. The default #000 (black).
color
Domstring string, converted to CSS color color value
gradient
Canvasgradient object (linear gradient or radioactive gradient)
pattern
Canvaspattern objects (REPEATABLE images)
ctx.strokeStyle = color || gradient || pattern
- The color and style of the graphics edge. Default #000 (Black)
Gradients and Patterns
CanvasGradient ctx.createLinearGradient(x0, y0, x1, y1);
- Creates a gradient of a line specified along the parameter coordinates
CanvasGradient ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
- Creates a radioactive gradient of a line specified along the parameter coordinates
CanvasPattern ctx.createPattern(image, repetition);
- Creates a pattern using the specified picture (a canvasimagesource)
image
An object that is a duplicate image source CanvasImageSource
repetition
Domstring, specifies how the image is repeated. The allowed values are: "Repeat" (both directions), "repeat-x" (horizontal only), "repeat-y" (vertical-only), "No-repeat" (neither).
Shadow
ctx.shadowBlur = level;
- Describes the blur effect. Default 0
ctx.shadowColor = color;
- The color of the shadow. Default Fully-transparent Black
ctx.shadowOffsetX = offset;
- The offset in the horizontal direction of the shadow. Default 0
ctx.shadowOffsetY = offset;
- The offset in the vertical direction of the shadow. Default 0
Transform
Objects in the CanvasRenderingContext2D
rendered background will have a current transformation matrix, which can be controlled by some methods. This transformation matrix is applied when creating the current default path, drawing text, graphics, and path2d objects. For details, refer to: Canvas graphics transformation
void ctx.rotate(angle);
- Increases the rotation in the transformation matrix, which represents a clockwise rotation angle and is expressed in radians
angle
The arc that rotates clockwise. If you want to calculate by angle value, you can use the formula: Degree * math.pi/180
void ctx.scale(x, y);
- Adds a zoom transform to the canvas unit based on the x horizontal and y vertical directions
void ctx.translate(x, y);
- Add a translation transformation by moving the canvas and canvas Origin x horizontal, Origin y vertically in the grid
void ctx.transform(m11, m12, m21, m22, dx, dy);
- Use the matrix described by the method parameter to overlay the current transformation matrix multiple times.
m11
Horizontal Scaling
m12
Tilt in horizontal direction
m21
Tilt in the vertical direction
m22
Vertical orientation of scaling
dx
Horizontal direction of movement
dy
Move in a vertical direction
void ctx.setTtransform(m11, m12, m21, m22, dx, dy);
- Re-sets the current transformation to the unit matrix and invokes the method with the same variable
transform()
void ctx.resetTransform();
- To reset the current transformation using the unit matrix
Synthesis
Specifies the combination of two or two graphs drawn before and after each other. Detailed instructions can be found here: Canvas using pictures, graphic combinations and cropping
ctx.globalAlpha = value;
- Sets the value of the graphics and image transparency before compositing to the canvas. The default is 1.0 (opaque).
ctx.globalCompositeOperation = type;
globalAlpha
set how to draw graphics and images on existing bitmaps by applying
Image-related
Set the interaction between the picture and canvas, detailed instructions can refer to here: Canvas image Preservation
Drawing an image
drawImage
method is used to draw an image on a canvas in the following three forms:
void ctx.drawImage(image, dx, dy);
void ctx.drawImage(image, dx, dy, dWidth, dHeight);
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
The parameters of the above methods have the following meanings:
image
Draws the element to the context. Allow any canvas image source (Canvasimagesource), for example: Htmlimageelement,htmlvideoelement, or Htmlcanvaselement
dx
The X-axis position of the upper-left corner of the target canvas
dy
The position of the Y-axis on the target canvas in the upper-left corner of the
dWidth
Draws the width of the image on the target canvas. Allows you to scale the drawn image. If not, the width of the picture does not scale when drawing
dHeight
The height of the image to draw on the target canvas. Allows you to scale the drawn image. If not, the height of the picture does not scale when drawing
sx
The X-coordinate of the upper-left corner of the rectangular selection box of the source image that needs to be drawn into the target context
sy
The Y-coordinate of the upper-left corner of the rectangular selection box of the source image that needs to be drawn into the target context
sWidth
The width of the rectangle selection box for the source image that needs to be drawn into the target context. If not, the entire rectangle starts at the coordinates of SX and SY and ends at the lower right corner of the image
sHeight
The height of the rectangle selection box for the source image that needs to be drawn into the target context
Pixel control
ImageData ctx.createImageData(width, height);
ImageData ctx.createImageData(imagedata);
- Creates a new, blank, ImageData object of the specified size. All the pixels are transparent in the new object.
width
ImageData
the width of the new object
height
ImageData
height of new object
imagedata
From an existing ImageData object, copy an object with the same width and height. The image itself is not allowed to be copied.
ImageData ctx.getImageData(sx, sy, sw, sh);
- Returns an ImageData object that describes the implied pixel data in the canvas area, which is represented by a rectangle with a starting point (SX, SY), SW, and SH
void ctx.putImageData(imagedata, dx, dy, [ dirtyX, dirtyY, dirtyWidth, dirtyHeight ]);
- Draws the data from the existing ImageData to the bitmap. If a dirty rectangle is provided, only the pixels of the rectangle are drawn
dx
The position offset of the source image data in the target canvas (offset in the x-axis direction)
dy
The position offset of the source image data in the target canvas (offset in the y-axis direction)
dirtyX
Optional, in the source image data, the position of the upper-left corner of the rectangular area. The default is the upper-left corner of the entire image data (x-coordinate)
dirtyY
Optional, in the source image data, the position of the upper-left corner of the rectangular area. The default is the upper-left corner of the entire image data (y-coordinate)
dirtyWidth
Optionally, the width of the rectangular area in the source image data. The default is the width of the image data
dirtyHeight
Optional, in the source image data, the height of the rectangular area. The default is the height of the image data
Canvas status
The CANVASRENDERINGCONTEXT2D rendering environment contains the style state of multiple drawings (properties wired style, fill style, shadow style, Text style). The following methods will help you to use these states:
void ctx.save();
- Use the stack to save the current drawing style state, you can use to
restore()
restore any changes
void ctx.restore();
- Reverts to the most recent drawing style state, which is
save()
saved to the latest element in the state stack
ctx.canvas;
HTMLCanvasElement
a reverse reference to read-only. If canvas
it is not associated with an element, it may be null
.
The above saved and restored canvas states include:
- The current transformation matrix
- The current clipping region
- List of current dashed lines
- The current value of the following property:
strokeStyle
Wireframe Fill Style
fillStyle
Graphic Fill Style
globalAlpha
Global transparency
lineWidth
Line width
lineCap
Thread head (wire cap)
lineJoin
Line-to-hand mode
miterLimit
Diagonal Face limit ratio
lineDashOffset
Dashed offset
shadowOffsetX
Shadow x Offset
shadowOffsetY
Shadow y Offset
shadowBlur
Shadow Blur degree
shadowColor
Shadow color
globalCompositeOperation
Graphic Combination method
font
Font style
textAlign
How text is aligned
textBaseline
Text baselines
direction
Text direction
imageSmoothingEnabled
Whether graphic scaling is smooth
Original address: http://uusama.com/632.html
If there is anything wrong and missing place, welcome to help treatise.
Canvas API Summary