How to Join Two Canvas Rectangles with Single Line in React

Last Updated on by in React JS

HTML Canvas is s a graphical, rectangular surface that uses HTML5 JavaScript methods to create, render, and display captivating graphics, shapes with eye-catching animation, colors, and supports a wide array of browsers, including Google Chrome, Mozilla, Opera, and much more.

In this tutorial, we will demonstrate how to connect two rectangles using a single line using canvas shapes in React js application. This comprehensive tutorial will enhance your knowledge of joining two rectangles with a line and answer how to work with canvas objects using the canvas drawing API.

Apart from that, we will also cover basic React canvas concepts, such as how to build a canvas surface in React, how to use JavaScript to access the canvas element in a functional component, and how to draw a single line on HTML 5 Canvas graphic, and connect from one rectangle to another rectangle.

The HTML Canvas Graphics is user friendly, and a dynamic surface for designing interactive visual graphics on web pages. It offers flexibility to web developers to draw any type of shapes and add sense of movement and action on web pages, resulting in dynamic and realistic user experiences.

Let’s explore the process of how to join two rectangle lines using React function component, React hooks, and HTML5 Canvas APIs.

Build React Project

First, open a command prompt.

Move to the directory where you want to create your project.

Run the following command to create a new React project using Create React App:

npx create-react-app my-react-app

Navigate into the new directory:

cd my-react-app

Install UI Dependency

We are installing a traditional UI library — Bootstrap; it enhances the UI development process by providing user-friendly and browser friendly UI modules.

npm install bootstrap --legacy-peer-deps

You can avoid installing this library if you are comfortable writing custom CSS.

Create Function Component

A React function component is a JavaScript function that returns JSX. On top of that a function component is easy to create and doesn’t require additional code.

Create components/ folder, build a DrawCanvas.js file.

import React from 'react'

function DrawCanvas() {
  return (
    <div></div>
  )
}

export default DrawCanvas

Join Two Rectangles with Line

Now, here comes the most important part of this guide, we have coded down the most versatile and efficient method for connecting two rectangles with a single line in React.

Make sure to insert code in components/DrawCanvas.js file.

import React, { useEffect, useRef } from "react";

function DrawCanvas() {
  let canvas = useRef();
  let context = null;

  let shape = [
    { x: 100, y: 120, w: 150, h: 50 },
    { x: 120, y: 150, w: 50, h: 30 },
    { x: 30, y: 30, w: 70, h: 50 },
    { x: 250, y: 50, w: 60, h: 40 },
  ];

  let shapeConnect = [
    { pointOne: 1, lastBlockIdx: 2 },
    { pointOne: 2, lastBlockIdx: 3 },
  ];

  useEffect(() => {
    let canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;
    context = canvasEle.getContext("2d");
    cleanShape();
  }, []);

  let cleanShape = () => {
    context.clearRect(
      0,
      0,
      canvas.current.clientWidth,
      canvas.current.clientHeight,
    );
    shape.map((data) => fillShape(data));
    shapeConnect.map((data) => connectLines(data));
  };

  let connectLines = (data) => {
    var pointOne = shape[data.pointOne];
    var lastBlockIdx = shape[data.lastBlockIdx];
    context.beginPath();
    context.moveTo(pointOne.x + pointOne.w / 2, pointOne.y + pointOne.h / 2);
    context.lineTo(
      lastBlockIdx.x + lastBlockIdx.w / 2,
      lastBlockIdx.y + lastBlockIdx.h / 2,
    );
    context.stroke();
  };

  let fillShape = (data, style = {}) => {
    let { x, y, w, h } = data;
    let { backgroundColor = "#ff3a00" } = style;
    context.beginPath();
    context.fillStyle = backgroundColor;
    context.fillRect(x, y, w, h);
  };

  return (
    <div className="section">
      <h2 className="mb-3">
        Join Two Canvas Rectangles with Single Line in React
      </h2>
      <canvas ref={canvas}></canvas>
    </div>
  );
}

export default DrawCanvas;

Register New Component

Navigate to src/ directory, look for App.js file, open the file and place the given code line by line.

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import DrawCanvas from "./components/DrawCanvas";

function App() {
  return (
    <div className="container mt-3">
      <h2 className="mb-3">React Canvas Join Two Rectangles with Line Example</h2>
      <DrawCanvas />
    </div>
  );
}

export default App;

Start Development Server

To set up a new React application, we’ll require to follow certain steps.

Here’s a basic command that will help you get started the development server:

npm start

The above command compiles your React project and launch a development server.

Your app will be automatically served in a web browser.

React Canvas Join Two Rectangles with Line Tutorial

http://localhost:3000

Conclusion

By leveraging JavaScript and the HTML5 canvas methods, developers can programmatically create and influence graphical elements on the canvas, including rectangles and other geometrical shapes.

As far as, joining two rectangles with a single line in React or any other frontend framework, the canvas API provides multidimensional methods and properties to add this geometrical effect.