How to Draw Rectangle on HTML5 Canvas using React

Last updated on: by Digamber

In this tutorial, you will learn how to draw a rectangle shape on HTML5 canvas surface using React js, function component and bootstrap module.

HTML5 Canvas allows you create dynamic design and update graphics animation on a web page using JavaScript. You can create 2D and 3D graphics using canvas.

In this guide you will learn to draw a rectangle shape on Canvas surface. The canvas tag can be used to invoke canvas service on a HTML web page.

We have curated a series of steps that will help you draw geometrical rectangle shape using JavaScript. JavaScript grants the access on Canvas element.

By using function component we will learn to create a drawing surface; also make you familiar with easy techniques that can help you draw shapes, lines and curves on canvas element in React js.

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.

positronX.io - Tamso Ma Jyotirgamaya
Digamber

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