HTML5 Convas APIs, html5convas

Source: Internet
Author: User
Tags transparent color

HTML5 Convas APIs, html5convas
This article mainly introduces the HTML5 Convas APIs method details. This article lists most of the Convas APIs methods and provides Chinese comments for these methods. For more information, see

☆Canvas. getContext ('2d ')

You cannot draw directly in convas. You must use this method to obtain the two-dimensional space drawing.
Below.

☆Context. beginPath ()

Indicates to start creating a new path.

☆Context. isPointInPath (x, y)

Determines whether a point is in the path. This method is not applicable after the coordinate system is converted.

☆Context. moveTo (x, y)

It is equivalent to lift the paint brush from the canvas, move the pen tip out of the canvas, and then locate the pen tip in
(X, y) coordinates, start a new drawing at this new position.

☆Context. lineTo (x, y)

This is equivalent to moving the pen tip from the current Coordinate Position
Draw a line segment at (x, y) coordinates.

☆Context. stroke ()

After drawing on convas, some painting operations must call this method to allow
Display.

☆Context. save ()

This method saves the current status of convas, no matter whether you change the status of convas in the future,
You only need to save the convas status before making these changes, and then you can call
The context. restore () method is restored to the Saved state. Usually in a new plot
Or the original state of convas should be saved before the modification operation (no painting or change is made
), Each time after a new painting or modification operation ends, it is restored to the original state. This
This is conducive to subsequent painting operations.
In fact, many attributes and some methods and shapes of the context in the 2d drawing environment of canvas
State, the value of each attribute is changed (or use some methods to change the drawing state ),
The drawing status changes. If it is saved after each change, multiple statuses of one attribute will
Stored as a stack. You can call restore () multiple times in the stack order.
To return to the saved status.

☆Context. translate (x, y)

This method moves the current coordinate origin to (x, y.

☆Context. restore ()

Restore the convas status to the last saved status.

☆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
Origination of the path. However, the closePath also informs
The canvas that the current shape has closed or formed
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 in the closed path after setting the fill style. You do not need to call this method again
Context. stroke () method.

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

Draw and fill the rectangle area with the width and length (width, height) at (x, y. Tune
You do not have to call the context. stroke () method after using this method.

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

Draw a rectangular contour of the width and length (width, height) at (x, y.

☆Context. clearRect (x, y, width, height)

Position (upper left corner of the rectangle) in (x, y,), the 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
Creating animations and games using the HTML5 Canvas API.
Repeatedly drawing and clearing sections of the canvas, it
Is possible to present the compression sion of animation, and conflict
Examples of this already exist on the Web. However,
Create animations that perform smoothly, you will need
Utilize clipping features and perhaps even a secondary
Buffered canvas to minimize the flickering caused
Frequent canvas clears.

☆Context. drawImage ()

This method has three reloads to draw images on the canvas. The image source can be
The img tag in the page, an image object in JS, And a frame of video.
• Context. drawImage (img, x, y)
Image img is used to draw the image at (x, y. When the size of the canvas is greater than the image size
The entire image is drawn. When the image is larger than the canvas, the excess is cropped.
• Context. drawImage (img, x, y, w, h)
Use the image img to plot the rectangular area with the length and width (w, h) at (x, y. Image
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 image to (imgx, imgy
) (Imgw, imgh) area, drawn in the canvas position is (cx, cy)
Area where the image size is (cw, ch.
If the cropping area on the image exceeds the image range, an exception is thrown.
• Context. drawImage (video, vx, vy, vw, VL, cx, cy, cw, ch)
A video object is used as the drawing object, and the position on the captured video is (vx, vy
) A frame with a size of (vw, VL). It is drawn at the position of (cx, cy) on the canvas.
Small is the area of (cw, ch.
In addition, the first parameter of drawImage () can be another canvas.

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

This method obtains the size (width, height) from the position (x, y) in the canvas)
In a pixel area, the returned value is an ImageData object. ImageData has width,
Height and data attributes.
The data attribute is a pixel array. Each of the four consecutive elements in the array represents an image.
The four continuous elements in turn contain the color and transparency information of RGBA. Four consecutive RMB
A prime must belong to a pixel. The position of the first element is not random.
The pixel array is the area specified in the canvas in the order from top to bottom and from left to right.
Scan to obtain. The number of elements in the pixel array is width * height * 4. To obtain a specific
Location pixel information.
If the Web page using this method is opened as a local file in a browser, it will not work normally.
Work usually produces security errors ). You can upload files
Web server, and then request access to solve this problem. In addition, the involved images, JS and
HTML must be from the same domain name. However, IE9 can be accessed through local files.
An example is as follows:

The Code is as follows:
// Obtain a pixel Region
Var imageData = context. getImageData (0, 0, 3, 3); // 3x3
Grid </p> <p> var width = imageData. width;
// The position of a specific pixel in the pixel area
Var x = 2;
Var y = 2;
// Index of the corresponding elements of the green color in the pixel array
Var pixelRedindex = (Y-1) * (width * 4) + (x-1) * 4 );
Var pixelGreenindex = pixelRedindex + 1;
Var pixelBlueindex = pixelRedindex + 2;
Var pixelAlphaindex = pixelRedindex + 3; </p> <p> var pixel = imageData. data; // CanvasPixelArray </p> <p> 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 the size of (w, h), the meaning of the ImageData object
The same as the ImageData object obtained by getImageData.

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

Draws an ImageData object to a canvas (x, y. The last four parameters are optional.
Specifies the position and size of a cropped rectangle.

☆Context. createLinearGradient (x1, y1, x2, y2)

A linear gradient is generated between (x1, y1) and (x2, y2. For example:

The Code is as follows:
Var gradientName = context. createLinearGradient (-5,-50,
5,-50 );

☆Gradient. addColorStop (offset, color)

Used to set the gradient color at different positions in the gradient. The color argument
Is the color you want to be applied in the stroke or fill
The offset position. The offset position is a value
0.0 and 1.0, representing how far along the gradient line
The color shoshould be reached. For example:

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

Color can use the rgba (r, g, B, a) function in CSS to generate a transparent gradient, such:

The Code is as follows:
// Generate a 50% color transparency gradient
GradientName. addColorStop (0.2, 'rgba (0, 0, 0, 0.5 )');

☆Context. createRadialGradient (x0, y0, r0, x1, y1, r1)

A gradient area is generated 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 login ss
Area between the two circles.

☆Context. createPattern (img, 'repeatpattern ')

Use an image img to generate a path with the repeatPattern type
StrokeStyle or filled fillStyle. The repeatPattern value is acceptable.
Take one of repeat, repeat-x, repeat-y, and no-repeat. For example:

The Code is as follows:
Context. strokeStyle = context. createPattern (gravel,
'Repeat ');

The img parameter can also be another canvas or video

☆Context. scale (xMultiple, yMultiple)

The two parameters respectively specify the draw scaling factor of the object after the x and y directions, greater than 1
To zoom in, and between 0 and 1 to zoom out. If the value is negative, reflection, flip, and other effects can be achieved.
.

☆Context. rotate (angle)

It is used to rotate the context of the drawing environment, and uses the current coordinate origin as the conversion center, in radians
The Unit, combined with Math. PI. Clockwise rotation when angle is a positive value.
Rotate values in a counter-clockwise manner.

☆Context. transform (ScaleX, skewY, skewX, ScaleY, transX,
TransY)

This function is used to control the size and shear and position of the drawing object. It is a transformation matrix.
. ScaleX and ScaleY are scaled by x and y coordinates, respectively. SkewY is the control
The vertical shear of context. The value can be a positive or negative floating point or integer of any size.
In y '= y + skewY * x. SkewX controls the horizontal switch of context.
The value can be a positive or negative floating point or integer of any size, which is equivalent
X' = x + skewX * y. The last two parameters are equivalent to translate (x, y ).
The role of the two parameters.

☆Context. setTransform (ScaleX, skewY, skewX, ScaleY,
TransX, transY)

This method is similar to transform, but the transform method will
Transform, scale, and rotate
Effect. The setTransform method will apply the transformation from the original state of context, no
Composite with the previous transform. Therefore, context. setTransform (1, 0, 0, 1,
0, 0) restore the context transformation status to its original value.

☆Filltext (text, x, y, maxwidth)

Draw text with the filled content as text at (x, y) coordinates. Maxwidth is an optional parameter.
Number, used to limit the width of all text and the total size of text spacing, if all and spacing
If the width of a single text character exceeds this value, the width of the spacing between a single text character and the character will be compressed,
Individual Characters become slim and the spacing decreases. Can be combined with context. font,
Use attributes such as context. fillStyle and context. textAlign to draw filled text.

☆Stroketext (text, x, y, maxwidth)

Draw text with text in the path at (x, y) coordinates. Maxwidt is an optional parameter
Number, used to limit the width of all text and the total size of text spacing, if all and spacing
If the width of a single text character exceeds this value, the width of the spacing between a single text character and the character will be compressed,
Individual Characters become slim and the spacing decreases. Can be combined with context. font,
Context. textAlign, context. lineWidth, context. strokeStyle, etc.
Property to draw the path text.
For example:

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 is calculated based on the values of the current font, textAlign, and textBaseline.
The size of the text area. The text parameter is the text content used for drawing. This method
Returns a TextMetrics object. Currently, there is only one TextMetrics object.
Width attribute. More attributes may be provided in the future.

☆Context. rect (x, y, w, h)

Draw a rectangle with a width of w and a height of h at a vertex (x, y. The current vertex is ignored. But the rectangle is drawn.
(X, y) becomes the new current vertex.

☆Context. arc (x, y, radius, startAngle, endAngle,
Anticlockwise)

Draw an arc. X and y are the coordinates of the center of the arc; radius is the Arc radius;
StartAngle and endAngle are start radians and end radians, respectively, in radians,
The circumference rate π is represented by Math. PI. The radians whose values are 0 are horizontal to the right; anticlockwise
Indicates the direction of the radian. It is an optional parameter. It is a Boolean value. true indicates the direction of the arc. false indicates the clockwise direction.
Clockwise. The default value is false. This method can omit the lineTo method. In use
After this method draws an arc, the next path will start from the end endpoint of the arc.
.

☆Context. arcTo (x1, y1, x2, y2, radius)

The current vertex and (x1, y1) Form a line L1, (x1, y1) and (x2, y2) form another
Line L2, the current point and (x2, y2) form the third line L3. If the origin is (x1, y1,
L1 and L2 are coordinate axes, tangent to L1 and L2, radius is radius, and
On the circle O1 in the same quadrant, the tangent point of L1 is set to p1 and that of L2 is p2. P1 on circle O1
There are two arcs between p2, with a section of arc closer to the origin point (x1, y1) (also shorter on the circle ).
An arc) is the drawn arc.

In addition, a line segment is drawn between the current vertex and (x1, y1) and connected to the ARC.
Because the path is continuous, the line segments between the current point and (x1, y1) are drawn first, and
Draw an arc. Split point p2 to the next current point.
This method is often used to draw a rounded rectangle.

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

In the current coordinate and (x2, y2), draw a quadratic besell curve segment, bending degree from
(X1, y1) control. (X1, y1) is not in 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
Determine the characteristics of the curve.

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

Draw between the current vertex and (x, y) by the Control Point (cp1x, cp1y) and (cp2x, cp2y)
The cubic besell curve that controls the bending degree.

☆Context. clip ()

This method creates a editing area based on the last closed path.
(Clip region ). The editing area is equivalent to a mask, and the subsequent content is only
The part that falls into the editing area is displayed.

☆Context. isPointInPath (x, y)

Check whether the coordinates (x, y) are in the drawn path. Returns true or
False.

☆Canvas. toDataURL (type, args)

This method can convert a canvas to an image. The image is base64-encoded. For example
If no two parameters are specified, this method is called without a parameter. The converted image format is png.
.
• Type: Specifies the image format to be converted, such as image/png and image/jpeg.
• Args: optional parameter. For example, if the type is image/jpeg, The args can be
Between 0.0 and 0.1 to specify the image quality.
For example, the following code adds the drawn content in the canvas to a new browser window.
Open the port or tab:

The Code is as follows:
Var canvas = document. getElementById ("myCanvas ");
Window. open (canvas. toDataURL ("image/png "));

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.