How to Draw Horizontal Line on Canvas Surface in React

Last Updated on by in React JS

HTML Canvas is a digital (bitmapped) surface that allows web developers to draw visually stunning graphics on web pages, adding a sense of interactivity to your pages to demonstrate amazing user experiences. With the help of the HTML5 Canvas API, create the canvas and draw mesmerizing shapes, curves, lines, text, boxes, images, and much more.

This short and sweet, comprehensive guide bit-by-bit demystify how to draw a horizontal line on canvas surface in React application using a function component and Canvas JavaScript APIs.

Creating a straight line on canvas area is amazing simple with beginPath, moveTo, lineTo, and stroke methods, and here is the short introduction for each method, catering to your development needs.

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.

React Canvas Horizontal Line Example

Here is a series of steps that you can follow to get started with HTML5 Canvas development:

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

If you want to know more about HTML5 Canvas API, here is an amazing crash course created by Traversy Media.

Conclusion

In conclusion, drawing lines on a canvas in React is a simple and straightforward process. It can be achieved by creating an HTML5 canvas element, obtaining a context object, and using the moveTo() and lineTo() methods.

All in all, we explained how to create reusable components for drawing lines on a canvas component, making it easier to manage and maintain your code, and improving HTML5 Canvas performance in combination with React.