Draw a line on Canvas using React

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

Steps to draw a line on Canvas

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

1. Create a react application

Let’s create a react application using create-react-app. You can refer to the following link for more details.

Create React Application

2. Add the canvas and initialize the context

Now, 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 line

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

In the above code, we are drawing a line by passing two major parameters such as info and style. We have passed the starting point and ending point via info param and manage the color and width by passing into the second param.

Here x and y will be considered as the first point of the line and x1 and y1 will be considered as the end point of the line. We have used the moveTo() and lineTo() methods to draw a line.

4. Draw rectangle

Let’s draw a line 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 line on Canvas using React - Clue Mediator
Output – Draw a line 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 *