Home » How to Draw Rectangle on Image in React JS

How to Draw Rectangle on Image in React JS

react draw rectangle on image

Today in this blog post, we will learn how to draw rectangle on an image in React JS. To draw a rectangle shape on an image, we will initialize the canvas and set the desired image to the canvas background.

And then we will use the strokeRect() method to draw an outlined rectangle.

Draw Rectangle on an Image in React JS

1. Creating a Canvas Area

<div>
  <canvas
    ref={canvasRef}
    style={{
      width: "600px",
      height: "400px",
      background: "url('./bg-img.jpg')",
    }}
  />
</div>

Firstly we will add a canvas and set the width and height of our canvas. Also, we have set an image to the canvas background property. We have used the useRef hook to access the canvas element. 

Now we have created our canvas with a background image.

2. Drawing a Rectangle on an Image

import { useEffect, useRef } from "react";

function App() {
  const canvasRef = useRef();

  const drawRectangle = () => {
    const context = canvasRef.current.getContext("2d");
    context.strokeStyle = "white";
    context.lineWidth = 2;
    context.strokeRect(50, 30, 110, 90);
    context.strokeRect(170, 65, 100, 80);
  };

  useEffect(() => {
    drawRectangle();
  }, []);

  return (
<div>
  <canvas
    ref={canvasRef}
    style={{
      width: "600px",
      height: "400px",
      background: "url('./bg-img.jpg')",
    }}
  />
</div>
  );
}

export default App;

For drawing the rectangle shape, we have written the drawRectangle() function. Inside this function, we get the context of our canvas then set the stroke color to white and the lineWidth property to 2.

We use the strokeReact() method to draw a rectangular outline. The strokeReact() method takes the following parameters.

strokeReact(x, y, width, height);

x  – x-axis coordinate

y – y-axis coordinate

width – the width of the rectangle

height – the height of the rectangle

We are using the useEffect hook to invoke the drawRectangle() function.

To draw a filled Rectangle we can use the fillRect(x, y, width, height) method. And the clearRect(x, y, width, height) method will clear the specified area.

Also, check out

3. Output

react draw rectangle on canvas

As you can see in the output we have drawn two rectangles on the image using the strokeReact() method.

Conclusion

In this tutorial, we have learned how to draw a rectangle on an image using the strokeReact() method. Hope it was helpful.

Leave a Reply

Your email address will not be published.