How to Draw Rectangle on HTML5 Canvas using React 18

Last Updated on by in React JS

A rectangle is a two-dimensional shape with four sides. As a front-end developer, you may get the task of drawing rectangles on canvas surfaces.

In this tutorial, we will show you how to draw rectangle shapes on canvas surfaces using the HTML5 Canvas APIs.

The HTML5 Canvas API provides an array of diverse methods to draw common shapes, including rectangles, circles, lines, and arcs. These shapes can be customized in terms of size, color, and positioning, allowing you to create fundamental shapes to render graphics on web pages.

This code example has been carefully selected to provide you with the practical aspect of drawing canvas shapes in React. By using the Canvas API, you can create visually appealing and dynamic interfaces, adding interactivity to design.

React Js Write Text on HTML5 Canvas Example

  • 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

You must have node and npm installed on your computer.

Open the terminal, add the given command and hit enter to begin the installation of fresh React framework.

npx create-react-app my-react-app

Step inside the application folder.

cd my-react-app

Install Bootstrap Package

We have to install the bootstrap module using the given command.

npm i bootstrap --legacy-peer-deps

Create Component File

Further, we will require a component folder; hence, create the components/ folder along with a CanvasSurface.js file.

import React from 'react'

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

export default CanvasSurface

Create Canvas Rectangle

The useEffect hook invokes the rectangle drawing; we added some variables that are dynamically adding height and width to the rectangle shape in react canvas.

Update below code in components/CanvasSurface.js file.

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

function CanvasSurface() {
  const canvas = useRef();
  let context2d = null;

  useEffect(() => {
    const canElement = canvas.current;
    canElement.width = canElement.clientWidth;
    canElement.height = canElement.clientHeight;
    context2d = canElement.getContext("2d");
  }, []);

  useEffect(() => {
    const rectOne = { x: 30, y: 32, w: 80, h: 40 };
    const rectStyle = { borderColor: "blue", borderWidth: 5 };
    createRectangle(rectOne, rectStyle);
    const rectTwo = { x: 90, y: 110, w: 50, h: 70 };
    createRectangle(rectTwo);
    const rectThree = { x: 150, y: 50, w: 50, h: 120 };
    fillRectangle(rectThree, { backgroundColor: "orange" });
    const rectFour = { x: 160, y: 250, w: 100, h: 40 };
    fillRectangle(rectFour);
  }, []);

  const createRectangle = (data, style = {}) => {
    const { x, y, w, h } = data;
    const { borderColor = "black", borderWidth = 1 } = style;

    context2d.beginPath();
    context2d.strokeStyle = borderColor;
    context2d.lineWidth = borderWidth;
    context2d.rect(x, y, w, h);
    context2d.stroke();
  };

  const fillRectangle = (data, style = {}) => {
    const { x, y, w, h } = data;
    const { backgroundColor = "black" } = style;

    context2d.beginPath();
    context2d.fillStyle = backgroundColor;
    context2d.fillRect(x, y, w, h);
  };

  return (
    <>
      <canvas ref={canvas}></canvas>
    </>
  );
}

export default CanvasSurface;

Update Main Entry

Open the App.js file; next, you have to import the CanvasFile component; make sure to define the component in the app method.

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

function App() {
  return (
    <div className="container mt-3">
      <h2 className="mb-3">React Draw Rectangle Shape on Canvas Example</h2>
      <CanvasSurface />
    </div>
  );
}

export default App;

Start Development Server

Lastly, we have to execute the given command to run the development server.

npm start

Your app will be served on your default browser:

http://localhost:3000

How to Draw Rectangle on HTML5 Canvas using React

Conclusion

In this guide, we got a change to learn how to work with HTML5 Canvas in React js.

We learned how to create a rectangle shape on react js function component.

Canvas is popularly known for designing interactive games, data visualization, image editing.

The good thing about HTML5 Canvas is that; It supports almost every modern web browsers, that contains Chrome, Firefox, Safari, and Edge.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.