Graphic transformation of HTML5 canvas Basic Drawing, html5canvas
<Canvas> </canvas>It is a new label added in HTML5 for drawing graphics. In fact, this label is the same as other labels. Its special feature is that this label can obtain a CanvasRenderingContext2D object, we can use JavaScript scripts to control this object for plotting.
<Canvas> </canvas>It is just a container for drawing graphics. In addition to attributes such as id, class, and style, there are also attributes of height and width. There are three steps to draw an element on the <canvas> element:
1. Obtain the DOM object corresponding to the <canvas> element. This is a Canvas object;
2. Call the getContext () method of the Canvas object to obtain a CanvasRenderingContext2D object;
3. Call the CanvasRenderingContext2D object for plotting.
Graph Conversion
Translation:Context. translate (x, y). The receiving parameters are the source point, which translates x in the x axis and y in the y axis.
Scaling:Context. scale (x, y). The receiving parameters are x-axis scaled proportionally, and y-axis scaled proportionally.
Rotation:Context. rotate (angle), the receiving parameter is the angle of the coordinate axis rotation.
It should be noted that after the graph is changed, the next drawing is followed by the last state, so if you need to return to the initial state, you need to use context. save (); and context. restore (); to save and restore the current state:
Copy the content to the clipboard using JavaScript Code
- Var canvas = document. getElementById ("canvas ");
- Var context = canvas. getContext ("2d ");
- // Translate ()
- Context. save ();
- Context. fillStyle = "# 1424DE ";
- Context. translate (10, 10 );
- Context. fillRect (0, 0, 200,200 );
- Context. restore ();
- // Scale ()
- Context. save ();
- Context. fillStyle = "# F5270B ";
- Context. scale (0.5, 0.5 );
- Context. fillRect (200,200, 50 );
- Context. restore ();
- // Rotate ()
- Context. save ();
- Context. fillStyle = "# 18EB0F ";
- Context. rotate (Math. PI/4 );
- Context. fillRect (200,200, 10 );
- Context. restore ();
The effect is as follows:
Another thing related to graphic transformation is matrix transformation: context. transform (a, B, c, d, e, f, g ). The parameters are described as follows:
A horizontal scaling (1 by default)
B horizontal skew (0 by default)
C vertical skew (0 by default)
D Vertical Scaling (1 by default)
E horizontal displacement (0 by default)
F vertical displacement (0 by default)
You can verify the effects of each parameter on your own. I will not describe it here.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.