How to make a rectangle with rounded corners in Canvas

There is not function in the standard, but you can achieve it with four curves forming a right angle (and rounded).

Corners may be rounded by four quadraticCurve functions

This may be achieved by replacing the rect function by quadratic curves.

Requires a recent browser: Internet Explorer 9, Chrome, Firefox, Safari.

Code:

``function roundedRectangle(x, y, w, h){  var canvas = document.getElementById("canvas4");   var context = canvas.getContext("2d");  var mx = x + w / 2;  var my = y + h / 2;  context.beginPath();  context.strokeStyle="green";     context.lineWidth="4";     context.moveTo(x,my);  context.quadraticCurveTo(x, y, mx, y);  context.quadraticCurveTo(x+w, y, x+w, my);  context.quadraticCurveTo(x+w, y+h, mx, y+h);  context.quadraticCurveTo(x, y+h, x, my);        context.stroke();}roundedRectangle(10, 10, 200, 100);``

The curve goes from the middle of an angle to the other. But even if we can place the control points closer to the small side, it does not make a right angle.

For a right angle,  a curve and a straight line are combined

To do this we combine a straight line and a quadratic curve (or arc).

Code:

``````context.moveTo(x+radius, y);
context.lineTo(x+w-radius, y);
context.quadraticCurveTo(x+w, y, x+w, y+radius);``````

The value given to radius is roughly equivalent to the radius of the corner which is the quarter of a circle and is the starting point of the curve, following a straight line.

A true rounded corners rectangle is made of four of them

It is enough to combine four figures of this style to form a complete rectangle.

Final source code of the rectangle with rounded corners:

``````<canvas id="canvas6" width="400" height="120"></canvas>

<script type="text/javascript">
function roundRect(x, y, w, h, radius)
{
var canvas = document.getElementById("canvas6");
var context = canvas.getContext("2d");
var r = x + w;
var b = y + h;
context.beginPath();
context.strokeStyle="green";
context.lineWidth="4";
context.moveTo(x+radius, y);
context.lineTo(r-radius, y);
context.quadraticCurveTo(r, y, r, y+radius);
context.lineTo(r, y+h-radius);
context.quadraticCurveTo(r, b, r-radius, b);
context.lineTo(x+radius, b);
context.quadraticCurveTo(x, b, x, b-radius);
context.lineTo(x, y+radius);
context.quadraticCurveTo(x, y, x+radius, y);
context.stroke();
}
roundRect(10, 10, 200, 100, 20);
</script>
``````

This code size seems large but the function will be translated into bytecode by the JavaScript compiler.

Application

• Speech bubble. A rectangle with rounded corners (or an oval) is the starting point to build comic bubbles.

You should also know ...