Home > Article > Web Front-end > Detailed explanation of HTML5 Convas APIs methods_html5 tutorial skills
☆ canvas.getContext('2d')
You cannot draw directly in canvas, you must use this method to obtain the
underlying of its two-dimensional space drawing.
☆ context.beginPath()
indicates starting a new path drawing.
☆ context.isPointInPath(x, y)
Determine whether a certain point is on the path. This method does not work after the coordinate system has been transformed.
☆ context.moveTo(x,y)
is equivalent to lifting the brush from the drawing board, leaving the pen tip away from the drawing board, then positioning the pen tip at the
(x, y) coordinates, and starting a new drawing at this new position.
☆ context.lineTo(x, y)
is equivalent to the brush tip not leaving the drawing board. The brush tip moves from the current coordinate position to the
(x, y) coordinate to draw a line segment.
☆ context.stroke()
After drawing on the canvas, some drawing operations must call this method to allow the drawn content
to be displayed.
☆ context.save()
This method saves the current state of the convas, regardless of any changes to the convas in the future.
As long as you save the convas state before making these changes, you can call the
context.restore() method to restore it to the saved one later. state. Usually the original state of the canvas (without any drawing or changes
) should be saved before a new drawing
or modification operation, and restored to the original state each time after a new drawing or modification operation ends. This
will be helpful for future drawing operations.
In fact, many properties and some methods of canvas's 2d drawing environment context are related to the state
. When the value of each property is changed (or some methods are used to change the drawing state), the
drawing state is Change. If saved after each change, multiple states of an attribute will be saved in the form of a stack. You can call the restore() method multiple times in the order of the stack to return to the corresponding saved state. state.
This method moves the current coordinate origin to (x, y).
☆ context.restore()Restore the canvas state to the last saved state.
☆ context.closePath()This command is very similar in behavior to the lineTo
function, with the difference being that the destination isautomatically assumed to be the
origination of the path. However, the closePath also informs
the canvas that the current shape has closed or formed a
completely contained area. This will be useful for future
fills and strokes.
At this point, you are free to continue with more
segments in your path to create additional subpaths. Or you
can beginPath at any time to start over and clear the path
list entirely.
Fill the closed path after setting the fill style. There is no need to call the
context.stroke() method after calling this method.
Draw and fill a rectangular area with width and length (width, height) at (x, y). There is no need to call the context.stroke() method after calling
this method.
Draw a rectangular outline with width and length (width, height) at (x, y).
☆ context.clearRect(x, y, width, height)Clean the rectangular area whose position (upper left corner of the rectangle) is (x, y,) and size is (width, height)
.Remove any content from the rectangular area and reset it
to its original, transparent color.
The ability to clear rectangles in the canvas is core to
creating animations and games using the HTML5 Canvas API. By
repeatedly drawing and clearing sections of the canvas, it
is possible to present the illusion of animation, and many
examples of this already exist on the Web. However, to
create animations that perform smoothly, you will need to
utilize clipping features and perhaps even a secondary
buffered canvas to minimize the flickering caused by
frequent canvas clears.
This method has three overloads, which can draw images on canvas. The image source can be the img tag in the ☆ context.getImageData(x, y, width, height)
A pixel area, and the return value is an ImageData object. ImageData has three attributes: width, var width = imageData.width; var pixel = imageData.data; // CanvasPixelArray var red = pixel[pixelRedindex];
page, the image object in JS and a frame of the video.
•context.drawImage(img, x, y)
Draws an image with image img at (x, y). When the size of the canvas is larger than the image
, the entire image is drawn; when the image is larger than the canvas, the excess part is cropped.
•context.drawImage(img, x, y, w, h)
Draw a rectangular area with the length and width (w, h) using the image img at (x, y). The size of the image
will be changed to (w, h).
•context.drawImage(img, imgx, imgy, imgw, imgh, cx, cy,
cw, ch)
Use an img image as the drawing object, and crop the upper position of img to (imgx, imgy
) An area of size (imgw, imgh) is drawn at the position (cx, cy)
in the canvas and an area of size (cw, ch) is drawn.
If the cropped area on the image exceeds the image range, an exception will be thrown.
•context.drawImage(video, vx, vy, vw, vh, cx, cy, cw, ch)
Use a video object as the drawing object, and grab the upper position of the video (vx, vy
) A frame with a size of (vw, vh), draw an area with a size of (cw, ch) at the position (cx, cy) on the canvas.
In addition, the first parameter of drawImage() can also be another canvas.
height and data. The
data attribute is a pixel array. Each four consecutive elements in the array represents a pixel. The four consecutive elements contain RGBA color and transparency information in turn. Four consecutive elements
must belong to one pixel, and the position of the first element is not chosen arbitrarily.
The pixel array is obtained by scanning the specified area
in the canvas in order from top to bottom and from left to right. The number of elements in the pixel array is width * height * 4. To get pixel information for a specific
position.
If a web page that uses this method is opened as a local file with a browser, it will not work properly
and usually a security error will occur. This issue can be resolved by uploading the file to the
web server and then requesting access. Moreover, the images, JS and
HTML involved must come from the same domain name. However, IE9 can be accessed through local files.
An example is as follows:
grid
//The position of the specific pixel in the pixel area
var x = 2;
var y = 2;
//The green color is in the pixel array Index of the corresponding element
var pixelRedindex = ((y-1)*(width*4)) ((x-1)*4);
var pixelGreenindex = pixelRedindex 1;
var pixelBlueindex = pixelRedindex 2 ;
var pixelAlphaindex = pixelRedindex 3;
var green = pixel[pixelGreenindex];
var blue = pixel[pixelBlueindex];
var alpha = pixel[pixelAlphaindex];
Generate an ImageData object of size (w, h). The meaning of the ImageData object
is the same as the ImageData object obtained by getImageData().
Draw an ImageData object to the canvas at (x, y). The last four parameters are optional parameters, used to set the position and size of a cropping rectangle.
☆ context.createLinearGradient(x1, y1, x2, y2)
Produce a linear gradient between (x1, y1) and (x2, y2). For example:
Used in gradients to set gradient colors at different locations. The color argument is the color you want to be applied in the stroke or fill at
the offset position. The offset position is a value between0.0 and 1.0, representing how far along the gradient line
the color should be reached. Such as:
gradientName.addColorStop(1, '#552200');
☆ context.createRadialGradient(x0, y0, r0, x1, y1, r1)
Create a radial gradient area between two circles. The first three arguments
represent a circle centered at (x0, y0) with radius r0, and
the last three arguments represent a second circle centered
at (x1, y1) with radius r1. The gradient is drawn across the
area between the two circles.
☆ context.createPattern(img, 'repeatPattern')
Use an image img to generate a
strokeStyle style or a filled fillStyle style of a certain path with a repeat type of repeatPattern. The value of repeatPattern can
be one of repeat, repeat-x, repeat-y and no-repeat. For example:
The parameter img can also be another canvas or video
☆ context.scale(xMultiple, yMultiple)
The two parameters respectively specify the subsequent drawing scaling factor of the object in the x and y directions. If it is greater than 1,
means zooming in, and between 0 and 1 means zooming out. If it is a negative value, effects such as reflection and flipping can be achieved
.
☆ context.rotate(angle)
is used to rotate the drawing environment context, with the current coordinate origin as the rotation center, in radians
as the unit, and combined with Math.PI. When the parameter angle is a positive value, it rotates clockwise, and when it is a negative value, it rotates counterclockwise.
☆ context.transform(ScaleX, skewY, skewX, ScaleY, transX, transY)
. ScaleX and ScaleY are the scaling of the x and y coordinates respectively. skewY controls the vertical shear of the
context. Its value can be a positive or negative floating point or integer of any size, which is equivalent to
performing y'= y skewY * x on the ordinate. Skewer The last two parameters are equivalent to the two parameters
in translate(x, y).
☆ context.setTransform(ScaleX, skewY, skewX, ScaleY,
This method is similar to transform, but the transform method will be combined with the effects of transform, scale, and rotate methods that have been applied before, resulting in a complex compound transformation
be compounded with the previous transformation. Therefore, context.setTransform(1, 0, 0, 1,
0, 0) is commonly used to restore the context's transformation state to its original value.
☆ fillText (text, x, y, maxwidth)
, used to limit the width of all text and the sum of text spacing. If the width of all and spacing
exceeds this value, the width of a single text character and character spacing will be compressed.Individual characters become elongated and the spacing becomes smaller. Fill text can be drawn by combining context.font,
context.fillStyle, context.textAlign and other attributes.
☆ strokeText (text, x, y, maxwidth)
Draw text with path content text at (x, y) coordinates. maxwidt is an optional parameter , used to limit the width of all text and the sum of text spacing. If the width of all and spacing
exceeds this value, the width of a single text character and character spacing will be compressed.Individual characters become elongated and the spacing becomes smaller. Path text can be drawn by combining context.font,
context.textAlign, context.lineWidth, context.strokeStyle and other
properties.
For example:
☆ context.measureText("text")
This method calculates
the size of the area occupied by the text based on the current values of font, textAlign, and textBaseline. The text parameter is the text content used to draw. This method
returns a TextMetrics object. Currently, the TextMetrics object has only one
width property, and more properties may be provided in the future.
☆ context.rect(x, y, w, h)
Draw a rectangle with width w and height h at point (x, y). The current point is ignored. But after the rectangle is drawn
, (x, y) becomes the new current point.
☆ context.arc(x, y, radius, startAngle, endAngle,
anticlockwise)
Draw an arc. x, y are the coordinates of the center of the arc; radius is the radius of the arc;
startAngle, endAngle are the starting radian and ending radian respectively, in radians,
Pi is represented by Math.PI, and the value is 0 The arc is horizontal to the right; anticlockwise
indicates the direction of drawing the arc, which is an optional parameter, Boolean value, true is counterclockwise, false
is clockwise, and the default is false. Using this method, the lineTo method can be omitted. After using the
method to draw an arc, the subsequent path drawing will start from the end point of the arc
.
☆ context.arcTo(x1, y1, x2, y2, radius)
The current point and (x1, y1) form a line L1, (x1, y1) and (x2, y2) form another
line L2, and the current point and (x2, y2) form a third line L3. If (x1, y1) is taken as the origin,
L1 and L2 are the coordinate axes, the radius is radius that is tangent to L1 and L2, and is on the circle O1 in the same quadrant as the "line segment" L3, let The tangent point with L1 is p1, and the tangent point with L2 is p2. There are two arcs between p1
and p2 on circle O1. The arc closer to the origin (x1, y1) (also the shorter
arc on the circle) is the arc drawn.
, because the path drawing is continuous, the line segment between the current point and (x1, y1) will be drawn first Draw, then
and then draw the arc. The tangent point p2 becomes the next current point.
This method is often used to draw rounded rectangles.
Draw a quadratic Bezier curve segment between the current coordinates and (x2, y2), and the curvature is controlled by
(x1, y1). (x1, y1) is not on the curve segment.
the bezierCurveTo, arcTo, and arc functions. These curves
take additional control points, a radius, or angles to
determine the characteristics of the curve .
Draw a cubic Bezier curve with control points (cp1x, cp1y) and (cp2x, cp2y)
between the current point and (x, y) to control the curvature.
This method will create a clipping region
(clip region) based on the last closed path drawn. The clipping area is equivalent to a mask. Only the part of the content drawn in the future
that falls within the clipping area will be displayed.
Check whether the coordinates (x, y) are within the drawn path. The return value is true or
false.
This method can convert canvas to image, and the image is based on Base64 encoding. If
does not specify two parameters, this method is called without parameters, and the converted image format is png format
.
•type: Specify the image format to be converted, such as image/png, image/jpeg, etc.
•args: Optional parameters. For example, if type is image/jpeg, args can be a value between
0.0 and 0.1 to specify the quality of the image.
For example, the following code will open the drawn content in the canvas in a new browser window
or tab: