Html5 Canvas API, html5canvasapi
For details, click
1. the HTML Canvas API has two advantages: First, you do not need to store each element in the drawn image as an object, so the execution performance is very good. Second, it is relatively easy to implement the Canvas API based on the existing excellent 2D drawing APIs of other programming languages.
2. When you use the canvas Element on a webpage, it creates a rectangular area. By default, the area width of the rectangle is 300 pixels and the height is 150 pixels. However, you can also customize the size or set other features of the canvas element.
Copy code
1 <body> 2 <div> 3
Copy code
3. canvas is a row element.
Copy code
1 <! Doctype html> 2
Copy code
As shown in the same row, it is not difficult to find that canvas is an element in the row.
4. CSS and canvas
Like most HTML elements, canvas elements can also add borders by applying CSS to set the padding and margin, and some CSS attributes can be inherited by elements in the canvas. For example, for a font style, the style of the text added to the canvas is the same as that of the canvas element by default.
In addition, setting attributes for context in canvas also follows the CSS syntax. For example, applying color and font styles to context is the same as the syntax used in any HTML or CSS document.
5. In all browsers, only Internet Explorer does not support HTML5 Canvas. If you want to use canvas in Internet Explorer, you can select an open-source project named assumercanvas. When using assumercanvas, you must first determine whether the current browser is Internet Explorer. If so, embed the script tag in the page to load the assumercanvas. The statement is as follows:
1
6. Pass in "2d" to get a two-dimensional context, which is the only available context so far. It is suggested that a standard may be added to support 3D context in a future version.
7. Many operations on the context are not immediately reflected on the page. BeginPath, moveTo, and lineTo functions do not directly modify the canvas display results. In canvas, many functions used to set the style and appearance do not directly modify the display result. The result is displayed only when the stroke or fill method is applied to the path.
8. Draw a circle. Call method: context. arc (100,100, 50, 0, 1/2 * Math. PI, true); parameters are represented in sequence: center x coordinate, center y coordinate, radius, start radian, end radian, clockwise or counterclockwise (true indicates clockwise, false indicates clockwise ). 1/2Math. PI indicates the radians of the 1/4 circle.
9. Transform (scaling, translation, rotation, etc)
As the mainstream image editing tools currently support real-time image processing, the complexity of this part of the content in the API is necessary.
Copy code
1 <! Doctype html> 2
Copy code
10. closePath. The behavior of this function is similar to lineTo. The only difference is that closePath automatically takes the starting coordinate of the path as the target coordinate. ClosePath also notifies the canvas that the currently drawn image has been closed or has formed a completely closed area, which is useful for future filling and stroke.
11. Stroke.
Copy code
1 // broaden the line 2 context. lineWidth = 4; 3 // The joining Point of the smooth path 4 context. lineJoin = 'round '; 5 // change the color to Brown 6 context. strokeStyle = '#663300'; 7 // Finally, draw the 8 context of the canopy. stroke ();
Copy code
You can also set the lineJoin attribute to bevel or miter (the corresponding context. miterLimit value also needs to be adjusted) to change the corner style.
LineCap, which can be set to butt, square, or round to specify the style at the end of the line.
12. strokeRect and clearRect. StrokeRect is used to draw the contour of a rectangle Based on the given position and coordinates. clearRect is used to clear all content in the rectangle area and restore it to its initial state, that is, transparent color. In the HTML5 Canvas API, the canvas's rectangle clearing function is the core function for creating animations and games. If you want to create an animation that runs smoothly, you need to use the clipping function. You may need to cache the canvas twice, to minimize the flickering image caused by frequent cleanup operations.
13. Draw a curve.
Copy code
1 <! Doctype html> 2
Copy code
The second group refers to the end point of the curve. The first group represents the control point ). The so-called control point is located next to the curve (not above the curve), and its function is equivalent to generating a tension on the curve. By adjusting the position of the control point, you can change the curvature of the curve. Other curves of the HTML5 Canvas API also involve bezierCurveTo, arcTo, and arc functions. These functions make curves more plasticity through multiple control points (such as radius and angle.
14. insert an image into the canvas. It is very easy to display images in a canvas. You can add a stamp, stretch an image, or modify an image at the correction layer, and the image usually becomes the focus of the canvas. You can easily add image content to the Canvas by using several simple commands built in the HTML5 canvas API. However, the image adds the complexity of the canvas operation: You must wait until the image is fully loaded before you can perform operations on it. Browsers usually load images asynchronously while executing page scripts. If you try to present an image to a canvas before it is fully loaded, the canvas will not display any image.
Copy code
1 <! Doctype html> 2
Copy code
We can see from the detailed code that we have added the onload processing function for the bark.jpg image to ensure that the image is loaded only. In addition to the image itself, the x, y, width, and height parameters are also specified. These parameters adjust the texture. We can also transfer the size of the source image to control the image in the cropping area.
15. gradient.
Three steps are required to use the gradient:
(1) create a gradient object;
(2) set the color of the gradient object and specify the transition mode;
(3) set a gradient for the fill style or stroke style in the context.
To set the color to display, use the addColorStop function on the gradient object. This function allows you to specify two parameters: Color and offset. The color parameter refers to the color that a developer wants to stroke or fill in at the offset position. The offset is a value between 0.0 and 1.0, representing how far is the gradient along the gradient line. In addition to changing to other colors, you can also set the alpha value (for example, transparency) for the color, and the alpha value can also be changed. To achieve this, you need to use another representation of the color value, such as the built-in CSS rgba function of the alpha component.
Copy code
1 <! Doctype html> 2
Copy code
In addition to the linear gradient we just used, the HTML5 Canvas API also supports radioactive gradient. The so-called radioactive gradient means that the color will change smoothly between the conical areas of the two specified circles. The color termination points used by the radioactive gradient and linear gradient are the same.
CreateRadialGradient (x0, y0, r0, x1, y1, r1)
In the code, the first three parameters represent the circle with (x0, y0) as the center and r0 as the radius. The last three parameters represent the center with (x1, y1) as the center, r1 is another circle with a radius. The gradient appears in the middle of the two circles.
16. background image.
Copy code
1 <! Doctype html> 2
Copy code
17. Scale the canvas object.
To draw a larger tree at a new position, we will use another transformation method-the zoom function context. scale
Copy code
1 <! Doctype html> 2
Copy code
The scale function has two parameters to represent the values in the x and y dimensions. When a canvas displays an image, each parameter is transmitted to the image to be enlarged (or reduced) in the current direction. If the value of x is 2, it means that all the elements in the image will be twice the width. If the value of y is 0.5, all the elements in the image will be half the height of the previous one. If you rotate an image that is not at the origin, the rotate function rotates the image around the origin instead of the original position. Similarly, if the image is not placed on the appropriate coordinates During Scaling, all path coordinates will be scaled at the same time. Depending on the size of the scaling ratio, the new coordinates may all be out of the canvas range, which may cause confusion for developers. Why does my scaling operation Delete the image ?"
18. Canvas transformation.
Copy code
1 <! Doctype html> 2
Copy code
19. Canvas text.
The canvas text is operated in the same way as other path objects: it depicts the text outline and fills in the text. At the same time, all the transformations and styles that can be applied to other graphics can be used for the text. The text rendering function of the context object consists of two functions:
(1) fillText (text, x, y, maxwidth)
(2) strokeText (text, x, y, maxwidth)
The parameters of the two functions are identical. required parameters include the text parameters and the coordinate parameters used to specify the text position. Maxwidth is an optional parameter used to limit the font size. It forcibly contracts the text font to the specified size. In addition, there is also a measureText function available, which returns a measurement object that contains the actual display width of the specified text in the current context environment.
To ensure that the text can be normally displayed in various browsers, Canvas API provides a CSS-like attribute for context to ensure that the actual display effect is highly configurable. Font (CSS font string, such as italic Arial, scan-serif), textAlign (start, end, left, right, center, default is start), textBaseline (top, hanging, middle, alphabetic, ideographic, bottom, default is alphabetic ).
Copy code
1 <! Doctype html> 2
Copy code
20. Application shadow.
You can control the shadow by using several global context attributes.
ShadowColor any color value in CSS. Available transparency (alpha)
ShadowOffsetX pixel value. The value is positive, and the shadow is moved to the right. The value is negative, and the shadow is moved to the left.
ShadowOffsetY pixel value. If the value is positive, the shadow is moved downward. If the value is negative, the shadow is moved upward.
ShadowBlur Gaussian Blur value. The greater the value, the blurrier the shadow edge.
Copy code
1 <! Doctype html> 2
Copy code
21. pixel data.
One of the most useful features of the Canvas API is to allow developers to directly access the underlying pixel data of the canvas. This data access is bidirectional: on the one hand, pixel data can be obtained in the form of a numerical array; on the other hand, the value of the array can be modified to apply it to canvas.
Context. getImageData (sx, sy, sw, sh ). This function returns the current canvas status and displays it as a numerical array. Specifically, the returned object includes three attributes.
Width: the number of pixels in each row.
Height: the number of pixels in each column.
Data: A one-dimensional array that contains the RGBA value of each pixel obtained from the canvas. This array saves four values for each pixel-red, green, blue, and alpha transparency. Each value ranges from 0 to 255. Therefore, each pixel on the canvas is converted into four integers in this array.
The getImageData function has four parameters. This function returns only the data in the region specified by these four parameters. Only pixels on the canvas in the rectangle area specified by the x, y, width, and height parameters are obtained. Therefore, to obtain all pixel data, you need to input the parameter as follows: getImageData (0, 0, canvas. width, canvas. height ).
Because each pixel is represented by four image data, it is a headache to calculate the value corresponding to the specified pixel. It doesn't matter. There is a formula below.
On the canvas with the given width and height, the pixel composition on the coordinate (x, y) is as follows.
Red part: (width * y) + x) * 4
Green part: (width * y) + x) * 4 + 1
Blue part: (width * y) + x) * 4 + 2
Transparency: (width * y) + x) * 4 + 3
After the red, green, blue, and alpha values of any pixel are modified, you can use the second function to update the display on the canvas, that is, context. putImageData (imagedata, dx, dy ). PutImageData allows developers to input a set of image data in the same format as the one obtained from the canvas. This function is very convenient to use, because you can directly obtain data from the canvas and modify it and then return it. Once this function is called, all new image data values are immediately updated and displayed on the canvas. The dx and dy parameters can be used to specify the offset. If used, the function will jump to the specified canvas position to update the pixel data that is passed in.
Finally, if you want to pre-create a group of empty canvas data, you can call context. createImageData (sw, sh). This function can create a group of image data and bind it to the canvas object. This set of data can be processed as before, but when canves data is obtained, this set of image data does not necessarily reflect the current status of canvas.
22. Canvas security mechanism.
The method for directly manipulating pixel data is discussed above. It is important to note that most developers use pixel data operations legally. However, some people may exploit this ability to directly obtain and modify data from the canvas for some evil purposes. For this reason, the concept of origin-clean canvas came into being. In other words, if the image in the canvas is not from the domain of the page containing it, the script in the page cannot obtain the data.
However, you cannot obtain the pixel information of the downloaded image programmatically before using the Canvas API. Private images from other websites can be displayed locally, but cannot be read or copied. If scripts are allowed to read image data outside of the local device, user photos and other sensitive online image documents on the entire network will be "unrestricted ".
To avoid this, when the getImageData function is called, if the image in the canvas is from another domain, a security exception is thrown. In this way, as long as you do not obtain the canvas data that shows images in other domains, You can render these remote images at will. Pay attention to this restriction during development and use a safe rendering method.
For more html5 content, click