Draw a rectangle for HTML5 canvas Basic Drawing, html5canvas
<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.
Draw rectangular rect (), fillRect (), and strokeRect ()
• Context. rect (x, y, width, height): defines only the path of the rectangle;
• Context. fillRect (x, y, width, height): draws a filled rectangle;
• Context. strokeRect (x, y, width, height): draws a rectangular border directly;
Copy the content to the clipboard using JavaScript Code
- <Script type = "text/javascript">
- Var canvas = document. getElementById ("canvas ");
- Var context = canvas. getContext ("2d ");
- // Use the rect Method
- Context. rect (10, 10, 190,190 );
- Context. lineWidth = 2;
- Context. fillStyle = "# 3EE4CB ";
- Context. strokeStyle = "# F5270B ";
- Context. fill ();
- Context. stroke ();
- // Use the fillRect Method
- Context. fillStyle = "# 1424DE ";
- Context. fillRect (190,190 );
- // Use the strokeRect Method
- Context. strokeStyle = "# F5270B ";
- Context. strokeRect (values, 10, 190,190 );
- // Use both the strokeRect method and fillRect Method
- Context. fillStyle = "# 1424DE ";
- Context. strokeStyle = "# F5270B ";
- Context. strokeRect (190,190, 10 );
- Context. fillRect (610,10, 190,190 );
- </Script>
Here we need to explain two points: the first point is the sequence of drawing between stroke () and fill (). If fill () is drawn after, when the stroke border is large, it will obviously overwrite the border drawn by stroke (). The second point: when setting the fillStyle or strokeStyle attribute, you can use "rgba (0.2, 0) ". The last parameter of this setting is transparency.
There is also an area related to rectangular painting: Clear the rectangular area: context. clearRect (x, y, width, height ).
The receiving parameters are respectively the starting position of the rectangle and the width and length of the rectangle.
In the above Code, add:
Context. clearRect (600,100, 60 );
You can get the following results:
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.