react-cropper 사용하기

코딩하는 친구·2024년 7월 14일

라이브러리

목록 보기
1/1
post-thumbnail

이미지에서 원하는 부분만 크롭하고 싶을 때 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 : 이미지가 크롭될 때마다 실행되는 콜백함수를 지정할 수 있다.

이 밖에도 다양한 욥션을 설정할 수 있다.

crop 옵션 사용 시 주의점

  • 이미지 빈도: crop 옵션은 사용자가 크롭 영역을 조작할 때마다 매우 빈번하게 발생할 수 있다.

따라서 성능 저하를 방지하기 위한 처리를 해야 한다.

  • 이미지 품질: getCroppedCanvas 메서드를 사용하여 캔버스 데이터를 가져올 때, 해상도와 이미지 품질을 적절히 설정해야 한다.

위의 코드는 크롭 박스를 움직일 때마다 렉?이 걸리는 문제가 있다.
따라서 이러한 성능 저하를 방지하기 위한 처리를 해야 한다.

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

profile
부족한만큼 채워나가는 초보 개발자

0개의 댓글