Draw a rectangle on Canvas using React

Many developers in ReactJS struggle with the drawing element on canvas therefore we have come up with the new article where we show you how to draw a rectangle on Canvas using React.

Steps to draw a rectangle on Canvas

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

1. Create a react application

In the first step, we’ll create a react application using create-react-app. If you don’t know how to implement a react application then refer to this link.

2. Add the canvas and initialize the context

Let’s render the canvas element in the DOM and initialize the context of the canvas.

Here we have used the useRef and useEffect hooks to manage the canvas element. Check out the more example of the React Hooks.

You can also see that we have set the width and height of the canvas and initialize the context for further use.

Use the following style to design a canvas.

3. Function to draw a rectangle

Now we’ll write a function to draw a rectangle on Canvas using react code.

In the above code, we are handling two different parameters such as info and style to draw a rectangle using the rect method.

We’ll use the x, y, w as width and h as height from the info. We will also use the borderColor and borderWidth from the style to decorate the rectangle.

4. Function to draw a rectangle with background

Let’s write one more function to draw a rectangle with background color.

Same as the previous function, we will use the two different parameters info and style. But here we will use the fillRect method to draw a filled rectangle.

5. Draw rectangles

We’ll use the above two functions to draw rectangles on page load.

6. Output

Let’s combine all code together and see how it looks.

App.js

Run the project and check the output in the browser.

Output - Draw a rectangle on Canvas using React - Clue Mediator
Output – Draw a 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 *