In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to use HTML5 Convas APIs". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use HTML5 Convas APIs.
☆ canvas.getContext ('2d')
It is not possible to draw directly in convas, and this method must be used to obtain its two-dimensional drawing.
The following.
☆ context.beginPath ()
Indicates the start of a new path drawing.
☆ context.isPointInPath (x, y)
Determine whether a point is on the path. This method is not applicable after the coordinate system is transformed.
☆ context.moveTo (XBI y)
It is equivalent to lifting the brush from the artboard, leaving the tip of the artboard, and then positioning the tip of the pen in the
At the coordinates, start a new drawing at this new location.
☆ context.lineTo (x, y)
Equivalent to the brush tip does not leave the artboard, the brush tip moves from the current coordinate position to
At the coordinates, draw a line segment.
☆ context.stroke ()
After drawing on convas, some drawing operations must call this method to make the drawing inside the
Allow for display.
☆ context.save ()
This method saves the current state of convas, regardless of any future changes to convas
As long as you save the convas state before making these changes, you can call the
The context.restore () method returns to the saved state. Usually draw in a new paragraph
Or before modifying the operation, you should save the original state of convas (no drawing or change has been made)
To restore it to its original state at the end of each new draw or modify operation this
The sample is beneficial to the later drawing operation.
In fact, many properties and some methods of canvas's 2d drawing environment context
The value of each property is changed (or some method is used to change the drawing state)
The drawing state changes. If it is saved after each change, multiple states of a property will
Save in the form of stack. You can call the restore () party many times according to the order of the stack.
To return to the corresponding saved state.
☆ context.translate (x, y)
This method moves the current coordinate origin to (x, y).
☆ context.restore ()
Restores the convas 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 ()
Fills the closed path after the fill pattern is set. After calling this method, you do not have to call the
The context.stroke () method.
☆ context.fillRect (x, y, width, height)
Draw and fill a rectangular area with width and length of (width, height) at (x, y). Adjust
After using this method, you no longer need to call the context.stroke () method.
☆ context.strokeRect (x, y, width, height)
Draw a rectangular outline with a width and length of (width, height) at (x, y).
☆ context.clearRect (x, y, width, height)
Cleanup position (upper left corner of the rectangle) is (x, y,), size is (width, height)
The rectangular area of the
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 and can draw the image on canvas. The source of the image can be
The img tag in the page, the image object in JS, and a frame of video.
Context.drawImage (img, x, y)
The image is drawn with the image img at (x, y). When the size of the canvas is larger than the image
The whole image is drawn; when the image is larger than canvas, the extra part is cropped.
Context.drawImage (img, x, y, w, h)
A rectangular region with a length and width of (w, h) is drawn with the image img at (x, y). Image
Will be changed to (w, h).
Context.drawImage (img, imgx, imgy, imgw, imgh, cx, cy
Cw, ch)
Take an img image as the drawing object, and crop the position on the img to (imgx, imgy)
) the area with the size of (imgw, imgh), and the position drawn in the canvas as (cx, cy)
Draw an area of the size (cw, ch) at.
If the cropped region on the image is out of range, an exception is thrown.
Context.drawImage (video, vx, vy, vw, vh, cx, cy, cw, ch)
Take a video object as the drawing object, and grab the position on the video as (vx, vy)
) A frame with a size of (vw, vh), and a large drawing at (cx, cy) on the canvas
An area that is small (cw, ch).
In addition, the first parameter of drawImage () can also be another canvas.
☆ context.getImageData (x, y, width, height)
The method obtains the size (width, height) from the position (x, y) in the canvas.
A pixel area that returns an ImageData object. ImageData has width
Height and data are three attributes.
The data attribute is an array of pixels in which every four consecutive elements represent an image.
Element, the four consecutive elements in turn contain the color and transparency information of RGBA. Four consecutive elements
The element must belong to a pixel, and the position of the first element is not random.
The pixel array specifies the region in the canvas in order from top to bottom and left to right.
Scan to get. The number of elements in the pixel array is width * height * 4. To get a specific
Pixel information for the location.
It will not be normal for Web pages that use this method to be opened as local files in a browser.
Work, usually lead to security errors (security error). You can upload files to
Web server, and then request access to resolve the problem. And, the images involved, 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:
/ / get a pixel area
Var imageData = context.getImageData (0,0,3,3); / / 3x3
Grid
Var width = imageData.width
/ / the position of a specific pixel in the pixel area
Var x = 2
Var y = 2
/ / the index of the corresponding element of the green color in the pixel array
Var pixelRedindex = ((ymae1) * (width*4)) + ((xMur1) * 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
The same ImageData object obtained by getImageData ().
☆ context.putImageData (ImageData, x, y, x1, y1, w, h)
Draw an ImageData object on the canvas at (x, y). The last four parameters are available
Select the parameter to set 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). Such as:
The code is as follows:
Var gradientName = context.createLinearGradient (- 5,-50)
5-50)
☆ Gradient.addColorStop (offset, color)
Used in gradients to set gradient colors in 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 function in CSS to generate transparent gradients, such as:
The code is as follows:
/ / produces a 50% transparent gradient of color
GradientName.addColorStop (0.2, 'rgba (0,0,0,0.5)')
☆ context.createRadialGradient (x0, y0, R0, x1, y1, R1)
A radiant gradient region 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 across the
Area between the two circles.
☆ context.createPattern (img, 'repeatPattern')
Using an image img to generate a path of repeating type repeatPattern
StrokeStyle style or filled fillStyle style. The value of repeatPattern can
Take one of repeat, repeat-x, repeat-y and no-repeat. Such as:
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 specify the drawing scale of the object in the x and y directions, respectively, greater than 1.
To zoom in, between 0 and 1 is zoomed out. If the value is negative, you can achieve the effects of reflection, flipping and so on.
.
☆ context.rotate (angle)
Used to rotate the drawing environment context, with the current coordinate origin as the center of rotation, in radians
As a unit, use Math.PI in conjunction with. Rotates clockwise when the parameter angle is positive; otherwise,
Rotate counterclockwise when it is negative.
☆ context.transform (ScaleX, skewY, skewX, ScaleY, transX
TransY)
This function is used to control the size, shear and position of drawing objects, and is a kind of transformation matrix.
. The scaling of ScaleX and ScaleY in x and y coordinates, respectively. SkewY is the control.
The vertical shear of context, whose value can be a positive or negative floating point or integer of any size, equivalent to
On the ordinate, y = y + skewY * x. SkewX controls the horizontal cutting of context.
Variable, its value can be a positive or negative floating point or integer of any size, which is equivalent to the Abscissa
X-ray = x + skewX * y. The effect of the last two parameters is equivalent to that of translate (x, y)
The role of two parameters.
☆ context.setTransform (ScaleX, skewY, skewX, ScaleY
TransX, transY)
This method is similar to transform, but the transform method will be the same as previously applied
The effects of the past transform, scale and rotate methods are compound, resulting in a complex compound transformation.
Effect. The setTransform method applies the transition from the original state of the context, not
Recombine with the previous transformation. Therefore, context.setTransform (1,0,0,1) is commonly used.
0,0) restore the transition state of context to its original value.
☆ fillText (text, x, y, maxwidth)
Draw text filled with text at the (x, y) coordinate. Maxwidth is an optional parameter
Number, used to limit the width of all text and the sum of text spacing, if all and spacing
If the width exceeds this value, the width of a single text character and character spacing will be compressed
Individual characters become slender and spaced smaller. Can be combined with context.font,
Properties such as context.fillStyle, context.textAlign, etc., draw filled text.
☆ strokeText (text, x, y, maxwidth)
Draw text with the content of the path text at the (x, y) coordinate. Maxwidt is an optional parameter
Number, used to limit the width of all text and the sum of text spacing, if all and spacing
If the width exceeds this value, the width of a single text character and character spacing will be compressed
Individual characters become slender and spaced smaller. 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 current values of font, textAlign, and textBaseline.
The size of the area occupied by the text. The text parameter is the text content used for drawing. This method
Returns a TextMetrics object. Currently, there is only one TextMetrics object.
The width property, which may provide more properties in the future.
☆ context.rect (x, y, w, h)
Draw a rectangle with a width of w and a height of h at point (x, y). The current point is ignored. But rectangle drawing
After that (x, y) becomes the new current point.
☆ context.arc (x, y, radius, startAngle, endAngle
Anticlockwise)
Draw an arc. X, y are the center coordinates of the arc; radius is the radius of the arc
StartAngle,endAngle is the starting Radian and the ending Radian, respectively, in radians
Pi is expressed by Math.PI, and the Radian with a value of 0 is horizontal to the right; anticlockwise
Indicates the direction of drawing radians, is an optional parameter, Boolean value, true is counterclockwise, false
Clockwise, default is false. Using this method, you can omit the lineTo method. In use
After this method draws an arc, the next path drawing starts at the end of the arc.
.
☆ context.arcTo (x1, y1, x2, y2, radius)
The current point forms a line L1 with (x1, y1), and another with (x2, y2).
The line L2, the current point and (x2, y2) form the third line L3. If we take (x1, y1) as the origin
L1 and L2 are axes, tangent to L1 and L2, with a radius of radius, and with "segment" L3.
On the circle O1 in the same quadrant, let the tangent point with L1 be p1 and the tangent point with L2 be p2. P1 on circle O1
There are two arcs between p2 and the inner origin (x1, y1). The arc is also shorter on the circle.
An arc) is the arc drawn.
In addition, a line segment and an arc are drawn between the current point and (x1, y1).
Because the path drawing is continuous, the line segment between the current point and (x1, y1) is drawn first, tight
Then draw the arc. 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 at the current coordinates and (x2, y2), and the degree of curvature is determined by
(x1, y1) control. (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 between the current point and (x, y) by the control points (cp1x, cp1y) and (cp2x, cp2y)
A cubic Bezier curve that controls the degree of curvature.
☆ context.clip ()
This method creates a clip region based on the last closed path drawn.
(clip region). The clip region is equivalent to a mask, and the content drawn later is only
Only the parts that fall within the clip area will be displayed.
☆ context.isPointInPath (x, y)
Detects 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 into image, and the image is based on Base64 coding. Such as
If you do not specify two parameters, the method is called without parameters, and the converted image format is in png format.
.
Type: specifies the image format to convert, such as image/png, image/jpeg, and so on.
Args: optional parameter. 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 puts the drawn content in canvas in a new browser window
Open in the mouth or tab:
The code is as follows:
Var canvas = document.getElementById ("myCanvas")
Window.open (canvas.toDataURL ("image/png"))
At this point, I believe you have a deeper understanding of "how to use HTML5 Convas APIs". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.