How to use canvas in react js?

Hi Friends 👋,

Welcome To aHoisting!

To use canvas in react js, you have to use canvas tag to Initializes the canvas context and draw shapes that’s how you can use canvas in react js.

Today, I am going to show you, how to use canvas in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

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

Step 3: Create a Component.

You can use ref={canvasRef} to use canvas in react js.

<canvas ref={canvasRef} width={300} height={200} style={{ border: "1px solid black" }} />

Use canvas example.

The below code is an example of a React. You have to import react and use canvas tag to Initializes the canvas context and draw shapes to use canvas in react js.

App.js

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

const CanvasExample = () => {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");

    // Draw a rectangle
    context.fillStyle = "blue";
    context.fillRect(50, 50, 200, 100);

    // Draw text
    context.fillStyle = "white";
    context.font = "20px Arial";
    context.fillText("Hello, Canvas!", 80, 100);
  }, []);

  return <canvas ref={canvasRef} width={300} height={200} style={{ border: "1px solid black" }} />;
};

export default CanvasExample;

In the above code example, I have used the canvas tag to use canvas in react js.

Check the output of the above code.

React, use, canvas

All the best 👍