How HTML5 Canvas draws rectangles and triangles
This article mainly shows you "HTML5 Canvas how to draw rectangles and triangles", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "HTML5 Canvas how to draw rectangles and triangles" this article.
Rectangle
There are two ways to draw a Canvas rectangle, one is to draw a line with stroke (), and the other is to fill the rectangle directly with fillRect (). The latter method is more common and relatively simple, only need to specify the coordinates of the upper left corner and the lower right corner of the rectangle to draw a rectangle.
The example code for encircling a rectangle with a line is as follows:
Ctx.strokeStyle = "FF0000"; / / the line is red.
Ctx.lineWidth=2; / / Linewidth is 2 pixels
Ctx.fillStyle = "blue"; / / the filling color is blue
Ctx.moveTo (10, 10); / / give the path a starting point
Ctx.lineTo (10,400); / / give the path an end point, out to the left
Ctx.lineTo (400,400); / / give the path an end point and go below
Ctx.lineTo (400,10); / / give the path an end point, out on the right
Ctx.lineTo (10, 10); / / give the path an end point, above
Ctx.fill (); / / Note that fill () comes first and stroke () comes after, otherwise error will occur.
Ctx.stroke ()
One drawback of this method is that it cannot directly fill the blank area.
The example code for drawing a rectangle with the fill rectangle command is as follows:
Ctx.fillStyle = "blue"; / / the fill color is blue
Ctx.strokeStyle = "red"; / / the stroke is red
Ctx.lineWidth = 2
Ctx.fillRect (10,10,400,400)
Ctx.strokeRect (10,10,400,400)
Triangle
There is no specific method for drawing triangles, so it can only be achieved by drawing lines around the edges. The example code is as follows:
Ctx.fillStyle= "red"
Ctx.beginPath ()
Ctx.moveTo (125150)
Ctx.lineTo (300275)
Ctx.lineTo (300,025)
Ctx.fill ()
These are all the contents of the article "how to draw rectangles and triangles in HTML5 Canvas". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!