Javascript required
Skip to content Skip to sidebar Skip to footer

Github React Native Art Draw Circle

Draw a rectangle on Sheet using React

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

Steps to depict a rectangle on Canvas

  1. Create a react awarding
  2. Add the sail and initialize the context
  3. Function to draw a rectangle
  4. Function to draw a rectangle with background
  5. Describe rectangles
  6. Output

ane. Create a react application

In the first step, nosotros'll create a react application using create-react-app. If y'all don't know how to implement a react application then refer to this link.

2. Add the canvas and initialize the context

Let's return the canvas element in the DOM and initialize the context of the sheet.

Here nosotros take used the useRef and useEffect hooks to manage the sail element. Cheque out the more example of the React Hooks.

You tin also see that we accept set up the width and height of the sheet and initialize the context for further utilize.

Use the post-obit style to design a canvas.

3. Part to draw a rectangle

Now we'll write a function to draw a rectangle on Canvas using react lawmaking.

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

Nosotros'll apply the 10, y, west as width and h every bit acme from the info. We will also apply the borderColor and borderWidth from the style to decorate the rectangle.

4. Function to depict a rectangle with background

Let'southward write one more function to draw a rectangle with groundwork color.

Same every bit the previous function, nosotros will apply the ii different parameters info and style. But here we will employ the fillRect method to draw a filled rectangle.

v. Draw rectangles

We'll employ the above two functions to depict rectangles on page load.

half dozen. Output

Let's combine all code together and run across how information technology looks.

App.js

Run the projection and cheque the output in the browser.

Output - Draw a rectangle on Canvas using React - Clue Mediator
Output – Draw a rectangle on Sail using React – Clue Mediator

That's it for today.
Thank y'all for reading. Happy Coding..!!

Demo & Source Lawmaking

Github Repository StackBlitz Projection

If you found value in this article,
you can support us by ownership me a coffee! ☕

You may too like...

abbottcomitaxby.blogspot.com

Source: https://www.cluemediator.com/draw-a-rectangle-on-canvas-using-react