Use HTML5 canvan for Web plotting

Source: Internet
Author: User
Tags canvas rectangle

Start:
1. <canvas id = "canvas" width = "300" height = "200">
2. Fallback content, in case the browser does not support Canvas.
3. </canvas>
It must be noted that, because it is unable to ensure that all browsers used by users support the canvas Element, "Fallback content" must be added to the Development of canvas-based Web applications ", to remind users that they cannot normally experience this function, or suggest them download the latest browser.
Here, curious readers may ask, since this is a common DOM node, it means that the canvas size can be changed by directly changing its width or height attribute value? This is true, but, as mentioned earlier, canvas is a pixel-level plotting method. Therefore, once the canvas size is adjusted dynamically, canvas will be "reset" to a new initial state. Even the following operations will clear the bitmap in the canvas and restore all relevant attributes to the initial state. Of course, we can also use this as a tip to reset the canvas.
1. document. getElementById ("canvas"). width = document. getElementById ("canvas"). width;
 
Simple Drawing
Canvas-Based Drawing does not directly perform various drawing operations on the drawing screen created by the canvas tag, but relies on the Rendering Context provided by the screen ), all drawing commands and attributes are defined in the rendering context. The first thing to do after obtaining the corresponding DOM object through the canvas id is to get the rendering context object. The rendering context corresponds to the canvas one by one. No matter how many times the getContext () method is called on the same canvas object, the same context object is returned. Currently, all browsers that support the canvas label support 2D rendering context. You can use the following code to obtain the object.
 
Var context = document. getElementById ("canvas"). getContext ("2d ");
 
 
In addition, in the near future, developers will be able to get OpenGL-based 3D rendering context for 3D drawing in the canvas.
Unlike SVG, canvas supports only one type of basic graphics, and other shapes such as circles and polygon are drawn by paths. Listing 1 shows how to use the rectangular Drawing Method in the rendering context to complete the graph shown in Figure 1.
Example and description:
Listing 1. Drawing a canvas rectangle
<! Doctype html> Draw path
Before you start to draw a path, you must first make it clear that the rectangular drawing API is a real-time API. After the corresponding drawing function is executed, render the image on the screen instantly. However, this is not the case with the path drawing API. The complete path drawing process can be divided into the following two phases:
• Define path outlines:
Each canvas instance object has a path object. The process of creating a custom image is the process of constantly operating on the path object. Every time you start a new drawing task, you must first use the beginPath () method to reset the path object to the initial state, and then call the moveTo/lineTo and other draw line methods through a series of calls, draw the expected path, where the moveTo (x, y) method sets the starting coordinate of the drawing, while lineTo (x, y) and other line drawing methods can draw a straight line from the current starting point, the arc and the curve to the target position. The last step is also an optional step. It is to call the closePath () method to close the custom image. This method will automatically create a straight line from the current coordinate to the start coordinate.
• Draw a path
After defining the path outline, no path is displayed on the canvas screen. You can also modify the path. Once determined, you need to continue calling the stroke ()/fill () function to complete the last step of rendering the path to the screen. The contour color and fill color of the path are determined by the strokeStyle and fillStyle attributes.
 
1. <! Doctype html>
2. 3. 4. <script type = "text/javascript">
5. window. onload = function test (){
6. var canvas = document. getElementById ('canvas ');
7. if (canvas. getContext ){
8. var ctx = canvas. getContext ('2d '); // obtain the 2d rendering context
9. ctx. clearRect (400,500, 300); // clear all pixels in the rectangle with (200) as the upper left coordinate origin and *
10. ctx. fillStyle = '# 00f'; // you can specify the filling attribute of the rectangle. # 00f indicates the blue color.
11. ctx. strokeStyle = '# f00'; // set the line color of the rectangle. # f00 indicates the red color.
12. ctx. fillRect (50, 50, 150, 80); // fill a * 80 size rectangle with fillStyle
13. ctx. strokeRect (160, 90); // draw a non-filled rectangle with the color of the strokeStype attribute as the edge
14 .}
15. var canvas2 = document. getElementById ('canvas2 ');
16. if (canvas2.getContext ){
17. var ctx = canvas2.getContext ('2d ');
18. ctx. fillStyle = '# 00f ';
19. ctx. strokeStyle = '# f00 ';
20. ctx. beginPath ();
21. ctx. arc (, 50, 0, Math. PI, false); // draw a semi-circular arc
22. ctx. closePath (); // automatically draws a straight line to close the arc. If you do not call this method, only a half arc is displayed.
23. ctx. fill (); // you can try to comment out the fill or stroke function to observe the image changes.
24. ctx. stroke ();
25 .}
26 .}
27. </script>
28. 29. <body>
30. <canvas id = "canvas" style = "border: 1px solid # c3c3c3;">
31. Your browser does not support the canvas element.
32. </canvas>
33. <canvas id = "canvas2" style = "border: 1px solid # c3c3c3;">
34. Your browser does not support the canvas element.
35. </canvas>
36.
37. </body>
38. 2d Deformation
Another important concept in Canvas plotting is the Drawing State, which reflects the current instantaneous State of the rendering context, developers can quickly return to the previous attributes and deformation operations by saving or restoring the painting status. The painting status consists of the following three parts:
• Current deformation matrix)
• Current Cropping Area (clipping region)
• Attributes in the current context, such as strokeStyle, fillType, globalAlpha, and font.
It should be noted that the current path object and the current bitmap are not included in the painting state, and the path is a persistent object. As mentioned above, only beginPath () operations will be reset, while bitmap is the canvas attribute, not the rendering context.
Developers can use the save and restore methods to save and restore the canvas status. Each time the save method is called, the current status is pushed into the stack, the corresponding restore method will pop up a status from the stack and restore the current screen to this status. The painting state is widely used and important in the deformation operation of the canvas image, because calling a restore method is much easier than manually restoring the previous State. Therefore, A good habit is to save the canvas status before performing the deformation operation.
Common deformation operations of 2D drawing can be well supported in canvas, including translation, rotation, and Scale. Since all the deformation operations are based on the deformation matrix, developers always need to remember that, once the save/restore operation is not used to keep the original drawing state, subsequent drawing operations, all will be completed in the current deformation state of the application. Listing 3 draws the following screen using the translation and rotation methods.
 
1. <! Doctype html>
2. 3. 4. <script type = "text/javascript">
5. window. onload = function test (){
6. var canvas = document. getElementById ('canvas ');
7. if (canvas. getContext ){
8. var ctx = canvas. getContext ('2d '); // obtain the 2d rendering context www.2cto.com
9. ctx. clearRect (400,500, 300); // clear all pixels in the rectangle with (200) as the upper left coordinate origin and *
10. ctx. fillStyle = '# 00f'; // you can specify the filling attribute of the rectangle. # 00f indicates the blue color.
11. ctx. strokeStyle = '# f00'; // set the line color of the rectangle. # f00 indicates the red color.
12. ctx. fillRect (50, 50, 150, 80); // fill a * 80 size rectangle with fillStyle
13. ctx. strokeRect (160, 90); // draw a non-filled rectangle with the color of the strokeStype attribute as the edge
14 .}
15. var canvas2 = document. getElementById ('canvas2 ');
16. if (canvas2.getContext ){
17. var ctx = canvas2.getContext ('2d ');
18. ctx. fillStyle = '# 00f ';
19. ctx. strokeStyle = '# f00 ';
20. ctx. beginPath ();
21. ctx. arc (, 50, 0, Math. PI, false); // draw a semi-circular arc
22. ctx. closePath (); // automatically draws a straight line to close the arc. If you do not call this method, only a half arc is displayed.
23. ctx. fill (); // you can try to comment out the fill or stroke function to observe the image changes.
24. ctx. stroke ();
25 .}
26. var canvas3 = document. getElementById ('canvas3 ');
27. if (canvas3.getContext ){
28. var ctx = canvas3.getContext ('2d ');
29. ctx. translate (150,150, 80); // translate the canvas origin from ())
30. for (I = 1; I <= 2; I ++) {// draw both internal and external layers
31. if (I % 2) = 1) {ctx. fillStyle = '# 00f ';}
32. else {ctx. fillStyle = '# f00 ';}
33. ctx. save (); // keep the state consistent when you start to draw each layer
34. for (j = 0; j <= I * 6; j ++) {// number of points generated at each layer
35. ctx. rotate (Math. PI/(3 * I); // rotate the coordinate system clockwise around the current origin point Math. Pi/(3 * I)
36. ctx. beginPath ();
37. ctx. arc (0, 20 * I, 5, 0, Math. PI * 2, true );
38. ctx. fill (); // fill each vertex with the fillType Value
39 .}
40. ctx. restore ();
41 .}
42 .}
43 .}
44. </script>
45. 46. <body>
47. <canvas id = "canvas" style = "border: 1px solid # c3c3c3;">
48. Your browser does not support the canvas element.
49. </canvas>
50. <canvas id = "canvas2" style = "border: 1px solid # c3c3c3;">
51. Your browser does not support the canvas element.
52. </canvas>
53. <canvas id = "canvas3" style = "border: 1px solid # c3c3c3;">
54. Your browser does not support the canvas element.
55. </canvas>
56.
57. </body>
58.
From junmoxier

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.