I have literally tried very much to fix this error and nothing is currently working,
this is the code im using:
import "./styles.css";
import { useState } from "react";
import ReactCrop from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";
function App() {
const [src, setSrc] = useState(null);
const [crop, setCrop] = useState({ aspect: 16 / 9 });
const [image, setImage] = useState(null);
const [output, setOutput] = useState(null);
const selectImage = (file) => {
setSrc(URL.createObjectURL(file));
};
const cropImageNow = () => {
const canvas = document.createElement("canvas");
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = crop.width;
canvas.height = crop.height;
const ctx = canvas.getContext("2d");
const pixelRatio = window.devicePixelRatio;
canvas.width = crop.width * pixelRatio;
canvas.height = crop.height * pixelRatio;
ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
ctx.imageSmoothingQuality = "high";
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width,
crop.height
);
// Converting to base64
const base64Image = canvas.toDataURL("image/jpeg");
setOutput(base64Image);
};
return (
<div className="App">
<center>
<input
type="file"
accept="image/*"
onChange={(e) => {
selectImage(e.target.files[0]);
}}
/>
<br />
<br />
<div>
{src && (
<div>
<ReactCrop crop={crop} onChange={setCrop}>
<img src={src} onLoad={setImage} />
</ReactCrop>
<br />
<button onClick={cropImageNow}>
Finish Selected Image Mask For Text Edit
</button>
<br />
<br />
</div>
)}
</div>
<div>{output && <img src={output} />}</div>
</center>
</div>
);
}
export default App;
whenever i want to press the crop button to see the cropped image, I keep on getting the error
"Failed to execute 'drawImage' on 'CanvasRenderingContext2D' "
What I have seen is the output is null for some reason, I tried to set the output like this in the reactcrop :
<ReactCrop crop={crop} onChange={setCrop} onCropCompleted={setOutput} >
and then return the output, still doesn't work, I have seen that what im trying to do here working just fine in the old versions of react crop image but I really have to use the latest version because Im testing this at university pc's and I dont have very much access to reinstall NPM or make it compatiable with it.
Any idea on how to solve this?
this is also a sandbox link for immediate testing: DEBUG CODE HERE