I've been struggling for a while on this. I am using React with Fabric js and I am trying to resize / move an image a user uploaded. I also want to resize / move a shape I created as well. It unfortunately does not do that. In the other hand if I get an image straight from the url, it works. What am I doing wrong? Here is a simplified code example:
function App() {
const [canvas, setCanvas] = useState(null);
const handleFileUpload = (e) => {
const reader = new FileReader();
reader.onload = function (e) {
const image = new Image();
image.src = e.target.result;
image.onload = function () {
const img = new fabric.Image(image);
canvas.add(img).setActiveObject(img).renderAll();
};
};
reader.readAsDataURL(e.target.files[0]);
};
useLayoutEffect(() => {
const initCanvas = () =>
new fabric.Canvas("c", {
height: 800,
width: 800,
});
setCanvas(initCanvas());
}, []);
const addRect = () => {
const rect = new fabric.Rect();
rect.set({
height: 100,
width: 100,
fill: "red",
});
canvas.add(rect).setActiveObject(rect).renderAll();
};
return (
<div className="App">
<canvas id="c" />
<button onClick={addRect}>Rectangle</button>
<input
type="file"
accept=".doc,.ppt,.pdf,.mp4,image/*"
id="cameraInput"
name="cameraInput"
onChange={(e) => handleFileUpload(e)}
/>
</div>
);
}
Here is also a demo