DEV Community

Anlisha Maharjan
Anlisha Maharjan

Posted on • Originally published at anlisha.com.np on

Fabric.js in React — Draw bounding box in webcam preview using canvas events.

Fabric.js is a JavaScript library for HTML5 canvas. Using Fabric.js one can create object/shapes on canvas. We’ll be incorporating canvas events to draw bounding box over webcam component.

Step1 — Install Fabric.js & react-html5-camera-photo

npm i fabric react-html5-camera-photo
Enter fullscreen mode Exit fullscreen mode

Step2 — Create canvas & camera element

<Camera onTakePhoto={(uri) => {}} />
<canvas id="fabricEl" width="720" height="348"></canvas>
Enter fullscreen mode Exit fullscreen mode

Step3 — Initialize fabric.Canvas

import React, { useEffect, useState } from "react";
import Camera from "react-html5-camera-photo";
import { fabric } from "fabric";

const [canvas, setCanvas] = useState("");

const initCanvas = () =>
 new fabric.Canvas("fabricEl", {
  selection: false,
  stateful: true,
});

useEffect(() => {
 setCanvas(initCanvas());
}, []);
Enter fullscreen mode Exit fullscreen mode

Note that initCanvas function returns a fabric.Canvas object; invoked upon initial rendering of the DOM.

Step4 — Draw bounding box with canvas mouse events

Fabric supports a number of events to allow for interactivity and extensibility. In order to subscribe to events for a canvas we use the on method.

useEffect(() => {
 if (canvas) {
  var rectangle;
  canvas.on("mouse:down", function (e) {
    var pointer = canvas.getPointer(e.e);
    rectangle = new fabric.Rect({
     id: 1,
     top: pointer.y,
     left: pointer.x,
     width: 0,
     height: 0,
     originX: "left",
     originY: "top",
     fill: "rgba(255,0,0,0.3)",
     stroke: "rgba(255,0,0,1)",
     strokeWidth: 2,
     hasControls: true,
     hasRotatingPoint: true,
     hasBorders: true,
     transparentCorners: false,
     selectable: true,
     cornerSize: 10,
     cornerColor: "rgba(255,0,0,1)",
     borderColor: "rgba(255,0,0,1)",
     cornerStrokeColor: "rgba(255,0,0,1)",
     cornerStyle: "rect",
    });
    canvas.add(rectangle);
  });
 }
}, [canvas]);
Enter fullscreen mode Exit fullscreen mode

On mouse:down event of canvas we create a fabric.Rect object and add it to the canvas via canvas.add() method.

Final Code!

View the code on Gist.

Note on line 95, canvas.renderAll() re-renders both the upper and lower canvas layers on the DOM. The object:moving event is to restrict the bounding box rectangle within canvas boundary. The object:modified event calculates bounding box center x, center y, width and height.

Demo!

The post Fabric.js in React — Draw bounding box in webcam preview using canvas events. first appeared on Anlisha Maharjan.

Latest comments (0)