The CanvasRenderingContext2D.roundRect()
method of the Canvas 2D API adds a rounded rectangle to the current path.
The radii of the corners can be specified in much the same way as the CSS border-radius
property.
Like other methods that modify the current path, this method does not directly render anything. To draw the rounded rectangle onto a canvas, you can use the fill()
or stroke()
methods.
roundRect(x, y, width, height, radii)
This example creates a number of rounded rectangular paths using the roundRect()
method. The paths are then rendered using the stroke()
method.
HTML
<canvas id="canvas" width="700" height="300"></canvas>
JavaScript
First we create a context for drawing our rounded rectangles.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
The code below draws two rectangles, both starting from the point (10, 20) and with a width of 150 and a height of 100. The first rectangle is drawn in red and specifies a zero radius for all the corners using a number as an argument. The second is drawn in blue, and specifies a 40px radius as a single element in a list.
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.roundRect(10, 20, 150, 100, 0);
ctx.stroke();
ctx.strokeStyle = "blue";
ctx.beginPath();
ctx.roundRect(10, 20, 150, 100, [40]);
ctx.stroke();
Below the previous rectangle we draw another in orange that specifies the values of the radii of opposite corners.
ctx.strokeStyle = "orange";
ctx.beginPath();
ctx.roundRect(10, 150, 150, 100, [10, 40]);
ctx.stroke();
Finally, we draw two rounded rectangles that have four values for the radii and the same starting point. The difference here is that the second is drawn with a negative width.
ctx.strokeStyle = "green";
ctx.beginPath();
ctx.roundRect(400, 20, 200, 100, [0, 30, 50, 60]);
ctx.stroke();
ctx.strokeStyle = "magenta";
ctx.beginPath();
ctx.roundRect(400, 150, -200, 100, [0, 30, 50, 60]);
ctx.stroke();
Result
The result is shown below. For the two rectangles on the right, note how the bottom rectangle is drawn with a negative width, and how this flips the rectangle horizontally.