Reputation: 23
I am using react-image-crop to cropped my images and show the final result.
when I am try using below code then my image not render properly
<ReactCrop src={src} onImageLoaded={setImage} crop={crop} onChange={setCrop} />
but if I am try this code to cropped my image
<ReactCrop crop={crop} onChange={setCrop}> <img src={props.imageUrl} onLoad={setImage} alt="crop" /></ReactCrop>
my image show properly and cropper image but when I am trying to save image it's show me error (mention in below line)
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.
import { useState } from 'react';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
function ImageCropper() {
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} alt="crop" />
</ReactCrop>
<br />
<button onClick={cropImageNow}>Crop</button>
<br />
<br />
</div>
)}
</div>
<div>{output && <img src={output} />}</div>
</center>
</div>
);
}
export default ImageCropper;
Upvotes: 1
Views: 694