Draw a rounded Rectangle on Canvas using React

Today we’ll show you how to draw a rounded rectangle on canvas using React. In the previous article, we taught you how to draw a rectangle on Canvas using ReactJS.

Steps to draw a rounded rectangle on Canvas

  1. Create a react application
  2. Add the canvas and initialize the context
  3. Function to draw a rounded rectangle
  4. Draw rectangle
  5. Output

1. Create a react application

In the first step, we’ll create a simple react application using create-react-app. Refer to this link It will help you to create a react application.

2. Add the canvas and initialize the context

In the next step, we have to render the canvas element in the DOM and initialize the context of the canvas. Refer to the link below.

How to initialize the context of the canvas

3. Function to draw a rounded rectangle

Use the following function to draw a rectangle on Canvas using react code.

In the above code, we are handing three different parameters as info, radius and color to draw a rounded rectangle using the lineTo() and quadraticCurveTo() methods.

We’ll use the x, y, w as width and h as height from the info and also use the tr as top right, br as bottom right, bl as bottom left and tl as top left from the radius param.

4. Draw rectangle

Let’s draw a rounded rectangle by using the above method.

5. Output

Combine all code together and see how it looks.

App.js

Run the project and check the output in the browser.

Output - Draw a rounded Rectangle on Canvas using React - Clue Mediator
Output – Draw a rounded Rectangle on Canvas using React – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *