How to draw a rounded rectangle using HTML Canvas and JavaScript?

Spread the love

Sometimes, we want to draw a rounded rectangle using HTML Canvas and JavaScript.

In this article, we’ll look at how to draw a rounded rectangle using HTML Canvas and JavaScript.

How to draw a rounded rectangle using HTML Canvas and JavaScript?

To draw a rounded rectangle using HTML Canvas and JavaScript, we use the arcTo method.

For instance, we write

const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.arcTo(0, 100, 0, 0, 30);
ctx.arcTo(0, 0, 100, 0, 30);
ctx.arcTo(100, 0, 100, 100, 30);
ctx.arcTo(100, 100, 0, 100, 30);
ctx.fill();

to call arcTo to draw the rounded corners.

The first 4 arguments of it are the x-y coordinates of the start and end points respectively.

And the 5th argument is the radius.

Conclusion

To draw a rounded rectangle using HTML Canvas and JavaScript, we use the arcTo method.

Leave a Reply

Your email address will not be published.