Using EraserBrush in Fabric.js with React, getting 'fabric.EraserBrush is not a constructor' error
I am trying to use the EraserBrush from Fabric.js in my React application. Since the EraserBrush is not included in the default build of Fabric.js, I downloaded a custom build and included it in the node_modules/fabric/dist directory of my app. However, I am encountering the following error:
fabric__WEBPACK_IMPORTED_MODULE_1__.fabric.EraserBrush is not a constructor TypeError: fabric__WEBPACK_IMPORTED_MODULE_1__.fabric.EraserBrush is not a constructor
Here is a simplified version of my code:
import React, {useEffect, useState, useRef} from 'react';
import { fabric } from 'fabric';
const Whiteboard = () => {
const canvasRef = useRef(null)
let canvas;
useEffect(() => {
canvas = new fabric.Canvas(canvasRef.current);
canvas.setHeight(window.innerHeight);
canvas.setWidth(window.innerWidth);
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 5;
canvas.freeDrawingBrush.color = '#000000';
return () => canvas.dispose();
},[])
const handleColorChange = (newColor) => {
canvas.freeDrawingBrush.color = newColor;
canvas.renderAll();
}
const handleErase = () => {
canvas.freeDrawingBrush = new fabric.EraserBrush(canvasRef.current);
canvas.isDrawingMode = true;
}
const handleClear = () => {
canvas.clear();
canvas.renderAll();
}
return(
<div>
<div>
<button onClick={() => handleColorChange('#FF0000')}>Red</button>
<button onClick={() => handleColorChange('#00FF00')}>Green</button>
<button onClick={() => handleColorChange('#0000FF')}>Blue</button>
<button onClick={handleErase}>Erase</button>
<button onClick={handleClear}>Clear</button>
</div>
<canvas id='canvas' ref={canvasRef}/>
</div>
);
}
export default Whiteboard;
I have already followed the steps mentioned in the Fabric.js documentation, but I am still facing this issue. How can I resolve this error and successfully use the EraserBrush in my React application?