import React, { FC, useState, useRef, useCallback } from 'react';
import ReactCrop, { Crop } from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
import Icon from '../icon/Icon';
import Style from './CropImage.module.scss';
const CropImage: FC = () => {
const imgRef = useRef();
const [crop, setCrop] = useState<Crop>({
unit: 'px',
x: 130,
y: 36,
width: 320,
height: 320
});
const [result, setResult] = useState('');
const [imageSrc, setImageSrc] = useState<any>();
const [image, setImage] = useState<HTMLImageElement>();
const onSelectFile = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
const reader = new FileReader();
reader.addEventListener('load', () => setImageSrc(reader.result));
reader.readAsDataURL(event.target.files[0]);
}
};
const onLoad = useCallback((evt: any) => setImage(evt.target), []);
const getCroppedImg = () => {
if (image) {
const canvas = document.createElement('canvas') as HTMLCanvasElement;
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = crop.width;
canvas.height = crop.height;
canvas
.getContext('2d')!
.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width,
crop.height
);
const base64Image = canvas.toDataURL('image/jpeg');
setResult(base64Image);
}
};
return (
<div>
{!imageSrc ? (
<label className={Style.inputImage}>
<input type="file" accept="image/*" onChange={onSelectFile} />
<Icon id="attach" width={24} height={22} />
<span>Upload a photo</span>
</label>
) : null}
{imageSrc ? (
<div className={Style.cropWrapper}>
<ReactCrop crop={crop} onChange={(c) => setCrop(c)} aspect={1 / 1}>
<img ref={imgRef} src={imageSrc} onLoad={onLoad} />
</ReactCrop>
</div>
) : null}
{result ? (
<a href={result} download>
click
</a>
) : null}
</div>
);
};
export default CropImage;