It works if I adds the code into useEffect but on onClick no object is showing. I want to show canvas objects on onClick.
import { useEffect, useState } from 'react';
import { fabric } from 'fabric';
const Canvasbody = () => {
const canvas = new fabric.Canvas('canvas-main');
function RectB(canvi) {
const rect = new fabric.Rect({
height: 280,
width: 200,
fill: 'yellow',
});
canvi.add(rect);
}
return (
<>
<canvas
style={{ border: 'solid 1px #555' }}
id="canvas-main"
width="600px"
height="600px"
/>
<button onClick={() => RectB(canvas)}>Click me</button>
</>
);
};
Try using canvi.renderAll()
after adding rect
to canvas
in your function.