React Canvas Join Two Rectangles with Line Tutorial
In this tutorial, you will learn how to connect two rectangles using a single line in React.
To join two rectangle line in React we will use HTML5 Canvas, HTML5 JavaScript methods and a function component.
The canvas element is an ideal choice to draw graphics; It offers a visual surface that uses JavaScript APIs to render or display various shapes and graphics.
The HTML5 canvas element provides a robust and dynamic surface for designing interactive visual graphics on the web page.
This extensive tutorial help us uplift our knowledge on joining two rectangles with a line, we saw how to accomplish this task using the canvas drawing API.
In this comprehensive post, we will learn the basic technique:
To build a canvas surface in React.
To use JavaScript to access the canvas element in functional component.
To draw a single line from one rectangle to another rectangle.
How to Join Two Canvas Rectangles using a Single Line in React
In this project a user can draw a single line from one rectangle to other rectangle using HTML5 canvas and a React function component.
- Step 1: Create React App
- Step 2: Install Optional Package
- Step 3: Build Function Component
- Step 4: Join Two Rectangles with Line
- Step 5: Register New Component
- Step 6: Start Development Server
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 canContext = null;
let shapeBlock = [
{ 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 = [
{ initBlockIdx: 0, lastBlockIdx: 1 },
{ initBlockIdx: 2, lastBlockIdx: 3 },
];
useEffect(() => {
let canvasEle = canvas.current;
canvasEle.width = canvasEle.clientWidth;
canvasEle.height = canvasEle.clientHeight;
canContext = canvasEle.getContext("2d");
}, []);
useEffect(() => {
cleanShape();
}, []);
let cleanShape = () => {
canContext.clearRect(
0,
0,
canvas.current.clientWidth,
canvas.current.clientHeight,
);
shapeBlock.map((data) => fillShape(data));
shapeConnect.map((data) => drawConnector(data));
};
let drawConnector = (data) => {
var initBlockIdx = shapeBlock[data.initBlockIdx];
var lastBlockIdx = shapeBlock[data.lastBlockIdx];
canContext.beginPath();
canContext.moveTo(
initBlockIdx.x + initBlockIdx.w / 2,
initBlockIdx.y + initBlockIdx.h / 2,
);
canContext.lineTo(
lastBlockIdx.x + lastBlockIdx.w / 2,
lastBlockIdx.y + lastBlockIdx.h / 2,
);
canContext.stroke();
};
let fillShape = (data, style = {}) => {
let { x, y, w, h } = data;
let { backgroundColor = "#ff0000" } = style;
canContext.beginPath();
canContext.fillStyle = backgroundColor;
canContext.fillRect(x, y, w, h);
};
return (
<>
<canvas ref={canvas}></canvas>
</>
);
}
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.
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.