In the previous article I talked about how to draw rectangles and circles, and they all have native canvas drawing functions to complete. In this paper, the rounded rectangle is only simulated by other methods.
A normal rounded rectangle, let's first assume that the fillet of his Four corners is the same--because it's a good picture. By using the ability to split the face into lines, it is easy to see that the rounded rectangle is actually made up of 4 hook-like curves.
Mention hooks, if you have seen me introduce ArcTo article, then perhaps you will understand that this figure can be drawn with ArcTo.
When I say ArcTo, ArcTo has a feature that his 2nd line extension does not affect the lines he draws (in the last part above), which also provides a convenient way for us to draw rounded rectangles without worrying about deformation.
The following release of the canvas I found on the foreign web site to draw rounded rectangle method, should be the most efficient.
The code is as follows:
//Rounded RectangleCanvasRenderingContext2D.prototype.roundRect =function(x, Y, W, H, r) {if(w < 2 * r) r = W/2; if(H < 2 * r) r = H/2; This. Beginpath (); This. MoveTo (x+R, y); This. ArcTo (X+w, y, X+w, y+h, R); This. ArcTo (X+w, Y+h, X, y+h, R); This. ArcTo (x, y+h, x, Y, R); This. arcto (x, Y, x+W, y, R); //This.arcto (x+r, y); This. Closepath ();return This; }
The parameters of this function are, in turn, the x-coordinate, the y-coordinate, the width, the height, and the fillet radius. Pay particular attention to this last parameter-the fillet radius.
This method uses 4 times ArcTo to draw a rounded rectangle with the same radian for each corner. The coordinate point of this rounded rectangle is the same as the upper-left corner of the rectangle, but his pen point is not here, but instead:
You can get rid of one of these lines and see how this works.
Of course, remind, no matter what graphics, do remember to close the path--closepath, to avoid leaving hidden trouble.
This method finally has a return this, so that you can use the chain syntax, such as:
Ctx.roundrect (200,300,200,120,20). stroke (); You can get rid of him if you don't need it.
If you do not want to expand the CONTEXTRENDERINGCONTEXT2D prototype, you can also make this method another function.
When I discovered this function, I didn't even know what ArcTo was, so I didn't remember what site it was found on, it's not my original, thanks to the author.
In the previous article I have always stressed that this method draws the rounded corners of the rectangle are consistent, because the CSS3 in the Border-radius can easily draw each corner or even the adjacent edge of each corner of the arc of the round rectangle, let me find the canvas to draw irregular rounded rectangle method, But personally I think it's hard.
[Turn]html5 Canvas Drawing Tutorial (10)-Split the polygon into lines to simulate a rounded rectangle