How to draw a rounded rectangle using HTML Canvas?
To craft a rounded rectangle using an HTML canvas, utilize the following code snippet:
Adjust x
, y
, width
, height
, and radius
values to fit your requirements.
Taking it to the next level
The above answer gets you up and running. Yet, calling it a day at this stage would be like ordering a pizza and ignoring the extra toppings. Let's look at how we can add some flavor to our rectangular pie!
Handling the corners your way
Perhaps having different corner curvatures is something you fancy. It's as simple as modifying the drawRoundedRect
function to accept an array of radii:
Love thy neighbors (browsers)
Before going Picasso on your canvas, do check if the browser speaks your language. arcTo
and roundRect
compatibility differ like JavaScript frameworks. If not, polyfills are here to save the day:
Chaining ain't just for jewelry
To enhance readability and compactness, return ctx
from the drawing function for method chaining:
Handling awkwardness (i.e., disproportionate corners)
Don't let disproportionate corners cramp your style. Make radii adjust in relation to the rectangle size:
Mix it up with methods
Only Siths deal in absolutes, so don't limit yourself to arcTo
method. Combine lineTo()
, arc()
, and quadraticCurveTo()
for a veritable potpourri of corner styles:
Making Shapes, The Advanced Way
CanvasRenderingContext2D isn't a one-trick pony. Dive into advanced shapes and patterns, and make Mona Lisa proud!
UI Integration: Making it all work
Align these rectangles with your UI elements to provide a smooth user experience. Rounded rectangles should harmonize with your UI and NOT steal the show!
Was this article helpful?