
이미지에서 원하는 부분만 크롭하고 싶을 때 react-cropper 라이브러리를 사용하면 간단하게 구현할 수 있다.
react-cropper는 대표적인 JavaScript 크로핑 라이브러리인 cropper.js를 리액트용으로 포장한 버전이다. 이는 다양한 기능과 설정 옵션을 제공한다.
npm i react-cropper
다음과 같이 간단하게 구현할 수 있다.
import React, { useRef } from "react";
import Cropper from "react-cropper";
import "cropperjs/dist/cropper.css";
const App = () => {
const cropperRef = useRef(null);
const onCrop = () => {
const cropper = cropperRef.current?.cropper;
if (cropper) {
console.log(cropper.getCroppedCanvas().toDataURL());
}
};
return (
<Cropper
src="https://raw.githubusercontent.com/roadmanfong/react-cropper/master/example/img/child.jpg"
style={{ height: 400, width: "100%" }}
// Cropper.js options
initialAspectRatio={16 / 9}
guides={false}
crop={onCrop}
ref={cropperRef}
/>
);
};
export default App;
initialAspectRatio : crop 초기 종횡비를 정의한다.
guides : crop 에 파선을 표시한다.
crop : 이미지가 크롭될 때마다 실행되는 콜백함수를 지정할 수 있다.
이 밖에도 다양한 욥션을 설정할 수 있다.
따라서 성능 저하를 방지하기 위한 처리를 해야 한다.
위의 코드는 크롭 박스를 움직일 때마다 렉?이 걸리는 문제가 있다.
따라서 이러한 성능 저하를 방지하기 위한 처리를 해야 한다.
import React, { useRef } from "react";
import Cropper from "react-cropper";
import "cropperjs/dist/cropper.css";
const debounce = (func, delay) => {
let timeoutId;
return (...args) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func(...args);
}, delay);
};
};
const App = () => {
const cropperRef = useRef(null);
const onCrop = debounce(() => {
const cropper = cropperRef.current?.cropper;
if (cropper) {
console.log(cropper.getCroppedCanvas().toDataURL());
}
}, 200);
return (
<Cropper
src="https://raw.githubusercontent.com/roadmanfong/react-cropper/master/example/img/child.jpg"
style={{ height: 400, width: "100%" }}
// Cropper.js options
initialAspectRatio={16 / 9}
guides={false}
crop={onCrop}
ref={cropperRef}
/>
);
};
export default App;
debounce 함수는 지정된 delay 시간 동안 호출을 지연시키고, 그 시간 동안 다시 호출될 경우 이전 호출을 취소하고 새로 타이머를 시작한다.
이를 통해 크롭 이벤트가 빈번하게 발생하더라도 호출 빈도가 줄어들어 성능 문제가 해결된다.


https://www.npmjs.com/package/react-cropper
https://github.com/fengyuanchen/cropperjs#options