How to make a rectangle with rounded corners in canvas

This is not provided by the Canvas standard, but it can be obtained with four curves forming a straight (and rounded) angle.

Rectangle corners can be rounded with quadraticCurve

This can be done by replacing the rect function with four quadratic curves.

Requires a fresh browser: Edge, 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 runs from the middle on one side to the other. But even if you can position the control points closer to the small sides, we don't have a right angle .

For a right angle, the curve is combined with a straight line

To do this, a straight line and a quadratic curve (or arc) are combined.

Code:

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

The radius value is more or less equal to the radius of the angle, which is a quarter of a circle, and corresponds to the starting point of the curve in the extension of the straight line.

A true rounded rectangle combines four of these patterns

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

The final source code for the rounded rectangle is:


<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>

The size of the code seems incredible, but the bytecode created by the JavaScript compiler reduces it to a few instructions.

Application

As well as...