React Js Draw Line Shape on Canvas Surface Tutorial

Last updated on: by Digamber

In this tutorial, we will learn how to create or draw a line shape on canvas surface in React js using function component and HTML5 JavaScript API.

HTML5 canvas is a brilliant tool that helps to design or draw visual shapes in React.

HTML5 canvas methods offers handy yet intuitive APIs. Here are the methods that you are going to use: beginPath, moveTo, lineTo, and stroke.

The beginPath() is a useful method in the HTML5 Canvas API that is helpful in to start drawing a new path in the current drawing.

A path is a series of connected lines, curves, and other shapes that are drawn on the canvas.

The moveTo() is a profound method offered by HTML5; It’s a Canvas API that is used to move the begning point of a new sub-path in the current drawing.

A sub-path is a portion of a path that consists of connected lines, curves, and other shapes.

The lineTo() is a method in the HTML5 Canvas API that is used to draw a straight line from the current position of the drawing cursor to a new specified position.

The stroke() method is offered by HTML5 Canvas that is used to stroke the current sub-path with the stroke style specified in the canvas context.

How to Draw Line on HTML5 Canvas in React

Here are the series of steps that you can follow to draw line in React:

  • Step 1: Create React Project
  • Step 2: Install Bootstrap Package
  • Step 3: Create Component File
  • Step 4: Create Canvas Rectangle
  • Step 5: Update Main Entry
  • Step 6: Start Development Server

Create React Project

We need to have node and npm installed on our development system.

On your command-prompt, you need to type the command and execute the command to begin installing React application.

npx create-react-app my-react-app

Head over to the React app directory.

cd my-react-app

Install Bootstrap Package

Here is the single command that helps you install the latest version of bootstrap package in React.

npm install bootstrap --legacy-peer-deps

Create Component File

Next, build the new components/ folder, you have to create a CanvasBoard.js file.

Here is how a function component looks after defining the below code.

import React from 'react'
function CanvasBoard() {
  return (
    <div></div>
  )
}
export default CanvasBoard

Create Canvas Rectangle

Now comes the important part of this guide; we have to define couple of React hooks and custom functions along with HTML5 Canvas API.

Update below code in components/CanvasBoard.js file.

import React, { useEffect, useRef } from "react";
export default function CanvasBoard() {
  const canvasRef = useRef();
  let canvasContext = null;
  useEffect(() => {
    const dynamicWh = canvasRef.current;
    dynamicWh.width = dynamicWh.clientWidth;
    dynamicWh.height = dynamicWh.clientHeight;
    // get context of the canvas
    canvasContext = dynamicWh.getContext("2d");
  }, []);
  useEffect(() => {
    createLine({ x: 100, y: 10, x1: 10, y1: 10 }, { color: "black", width: 8 });
    createLine(
      { x: 10, y: 140, x1: 10, y1: 20 },
      { color: "orange", width: 3 },
    );
  }, []);
  const createLine = (info, data = {}) => {
    const { x, y, x1, y1 } = info;
    const { color = "black", width = 1 } = data;
    canvasContext.beginPath();
    canvasContext.moveTo(x, y);
    canvasContext.lineTo(x1, y1);
    canvasContext.strokeStyle = color;
    canvasContext.lineWidth = width;
    canvasContext.stroke();
  };
  return (
    <>
      <canvas ref={canvasRef}></canvas>
    </>
  );
}

Update Main Entry

Now, head over to the src/App.js file; register the CanvasBoard class by adding the CanvasBoard component in this main entry.

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import CanvasBoard from "./components/CanvasBoard";
function App() {
  return (
    <div className="container mt-3">
      <h2 className="mb-3">React Js Draw Line on Canvas Board Example</h2>
      <CanvasBoard />
    </div>
  );
}
export default App;

Start Development Server

In this final step, we will use the below command to start the application server.

npm start

Once the project is compiled, your app will be served on:

http://localhost:3000

React Js Draw Line Shape on Canvas Surface Tutorial

Conclusion

In conclusion, drawing lines on a canvas in React is a simple and straightforward process.

It can be obtained by creating a HTML5 canvas element, obtaining a context object, and using the moveTo() and lineTo() methods to draw the line.

In React, you can easily create reusable components for drawing lines on a canvas, making it easier to manage and maintain your code.

positronX.io - Tamso Ma Jyotirgamaya
Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.