Home > Web Front-end > H5 Tutorial > Detailed explanation of HTML5 Convas APIs methods_html5 tutorial skills

Detailed explanation of HTML5 Convas APIs methods_html5 tutorial skills

WBOY
Release: 2016-05-16 15:46:50
Original
1503 people have browsed it

☆ 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.

☆ context.translate(x, y)

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 is

automatically 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.

☆ context.fill();

Fill the closed path after setting the fill style. There is no need to call the

context.stroke() method after calling this method.


☆ context.fillRect(x, y, width, height)

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.


☆ context.strokeRect(x, y, width, height)

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.

☆ context.drawImage( )

This method has three overloads, which can draw images on canvas. The image source can be the img tag in the
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.

☆ context.getImageData(x, y, width, height)

This method obtains the size (width, height) from the position (x, y) in the canvas.

A pixel area, and the return value is an ImageData object. ImageData has three attributes: width,
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:



Copy the code The code is as follows:
// Get a pixel area
var imageData = context.getImageData(0, 0, 3, 3); // 3x3
grid

var width = imageData.width;
//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 pixel = imageData.data; // CanvasPixelArray

var red = pixel[pixelRedindex];
var green = pixel[pixelGreenindex];
var blue = pixel[pixelBlueindex];
var alpha = pixel[pixelAlphaindex];


☆ context.createImageData(w, h)

Generate an ImageData object of size (w, h). The meaning of the ImageData object

is the same as the ImageData object obtained by getImageData().


☆ context.putImageData(ImageData, x, y, x1, y1, w, h)

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:



Copy code
The code is as follows:
var gradientName = context.createLinearGradient( -5, -50,
5, -50);



☆ Gradient.addColorStop(offset, color)

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 between

0.0 and 1.0, representing how far along the gradient line
the color should be reached. Such as:

gradientName.addColorStop(1, '#552200');

Color can use the rgba(r,g,b,a) function in CSS to generate transparent gradients, such as:



Copy code
The code is as follows:

//Generate 50% color transparent gradient
gradientName.addColorStop(0.2, 'rgba(0, 0, 0, 0.5)');

☆ 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:

Copy code
The code is as follows:

context.strokeStyle = context.createPattern (gravel,
'repeat');

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)

This function is used to control the size, shear and position of the drawing object. It is a transformation matrix

. 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,

transX, transY)


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

effect. The setTransform method will apply the transformation from the original state of the context and will not

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)

Draw text filled with text at the (x, y) coordinates. maxwidth 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. 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:




Copy code
The code is as follows:
var fontSize = 100 ;
context.font = fontSize "px Arial";
while(context.measureText("Hello world!").width > 140)
{
fontSize--;
context .font = fontSize "px Arial";
}
context.fillText("Hello world!", 10, 10);
context.fillText("Font size is " fontSize "px", 10, 50);

☆ 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.

In addition, a line segment will be drawn to connect the arc between the current point and (x1, y1)

, 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.

☆ context.quadraticCurveTo(x1, y1, x2, y2)

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.

Other options for curves in the HTML5 Canvas API include

the bezierCurveTo, arcTo, and arc functions. These curves
take additional control points, a radius, or angles to
determine the characteristics of the curve .

☆ context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Draw a cubic Bezier curve with control points (cp1x, cp1y) and (cp2x, cp2y)

between the current point and (x, y) to control the curvature.

☆ context.clip()

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.

☆ context.isPointInPath(x, y)

Check whether the coordinates (x, y) are within the drawn path. The return value is true or

false.

☆ canvas.toDataURL(type, args)

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:


Copy the codeThe code is as follows:
var canvas = document.getElementById("myCanvas");
window.open(canvas.toDataURL("image/png "));

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template