In the previous article, I talked about the methods of drawing rectangles and circles. They all have native canvas drawing functions that can be completed. The rounded rectangle mentioned in this article can only be simulated through other methods.
For a normal rounded rectangle, let's first assume that the rounded corners of its four corners are the same - because this is easier to draw. We use the ability to split the surface into lines and it is easy to find that the rounded rectangle is actually composed of 4 hook-like curves.
Speaking of hooks, if you have read my article introducing arcTo, then you may immediately understand that this kind of graphics can be drawn using arcTo.
When I talked about arcTo, I mentioned that arcTo has a characteristic that its second tangent extension will not affect the lines he draws (in the last part above), which also provides convenience for us to draw rounded rectangles without worrying about deformation.
The following is the method of drawing rounded rectangles that I found on a foreign website, which should be the most efficient.
//Round rectangle
CanvasRenderingContext2D.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 x coordinate, y coordinate, width, height, and rounded corner radius. Pay special attention to the last parameter - rounded corner radius.
This method uses arcTo 4 times to draw a rounded rectangle, and the arcs of each corner are the same. The coordinate point of this rounded rectangle is also the same upper left corner as the rectangle, but its starting point is not here, but:
You can remove one of the lines and see how this method is.
Of course, I would like to remind you that no matter what shape you draw, you must remember to close the path - closePath to avoid leaving hidden dangers.
This method has a return this at the end, which allows you to use chain syntax, such as:
ctx.roundRect(200,300,200,120,20).stroke(); You can remove it if you don't need it.
If you don't want to expand the ContextRenderingContext2D prototype, you can also use this method to make another function.
When I discovered this function, I didn't even know what arcTo was, so I didn't remember which website I found it on. Anyway, it was not original by me. Thanks to the author.
In the previous article, I have always emphasized that each corner of the rounded rectangle drawn in this method is consistent because border-radius in css3 can easily draw rounded rectangles with inconsistent arcs of each corner or even each corner. I will find a way to draw irregular rounded rectangles in canvas, but I personally think it is quite difficult.