본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Image Cropper — 확대·회전·종횡비로 이미지 자르기

원문 보기 위키 갱신

확대(zoom), 회전(rotation), 종횡비(aspect ratio) 컨트롤로 이미지를 자르고 변형하는 컴포넌트예요. 프로필 사진, 썸네일 등 다양한 이미지 편집에 사용할 수 있어요.

출처: 문서

본문

구조 (Anatomy)

<ImageCropper.Root>
  <ImageCropper.Viewport>
    <ImageCropper.Image />
    <ImageCropper.Selection>
      <ImageCropper.Handle />
      <ImageCropper.Grid />
    </ImageCropper.Selection>
  </ImageCropper.Viewport>
</ImageCropper.Root>

예제 (Examples)

기본 (Basic)

기본 이미지 크로퍼를 설정해요. 핸들을 드래그해 선택 영역을 조절하거나, 내부를 드래그해 이미지를 팬할 수 있어요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import styles from 'styles/image-cropper.module.css'

export const Basic = () => {
  return (
    <div className={styles.Layout}>
      <ImageCropper.Root className={styles.Root}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

종횡비 (Aspect Ratio)

크롭 영역을 특정 종횡비로 고정해요. aspectRatio 프롭을 사용하세요. 와이드스크린은 16/9, 정사각형은 1 같은 숫자를 넘겨요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import { RectangleHorizontalIcon, SquareIcon, RectangleVerticalIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

const aspects = [
  { label: '16:9', value: 16 / 9, icon: RectangleHorizontalIcon },
  { label: '1:1', value: 1, icon: SquareIcon },
  { label: '9:16', value: 9 / 16, icon: RectangleVerticalIcon },
]

export const AspectRatio = () => {
  const [aspectRatio, setAspectRatio] = useState(16 / 9)

  return (
    <div className={styles.Layout}>
      <div className={button.Group}>
        {aspects.map((aspect) => (
          <button
            key={aspect.label}
            className={button.Root}
            data-variant={aspectRatio === aspect.value ? 'solid' : undefined}
            onClick={() => setAspectRatio(aspect.value)}
          >
            <aspect.icon />
            {aspect.label}
          </button>
        ))}
      </div>

      <ImageCropper.Root className={styles.Root} aspectRatio={aspectRatio}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

원형 크롭 (Circle Crop)

프로필 사진이나 아바타에는 cropShape="circle"을 사용하세요. 선택 영역이 사각형 대신 원이 돼요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import styles from 'styles/image-cropper.module.css'

export const Circle = () => {
  return (
    <div className={styles.Layout}>
      <ImageCropper.Root className={styles.Root} cropShape="circle">
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

초기 크롭 (Initial Crop)

initialCrop 프롭으로 미리 정의된 크롭 영역에서 시작할 수 있어요. 픽셀 단위의 x, y, width, height를 가진 객체를 넘겨요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import styles from 'styles/image-cropper.module.css'

export const InitialCrop = () => {
  return (
    <div className={styles.Layout}>
      <p className={styles.Description}>Starts with a pre-defined crop area</p>

      <ImageCropper.Root className={styles.Root} initialCrop={{ x: 50, y: 30, width: 200, height: 120 }}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

제어된 확대 (Controlled Zoom)

zoom과 onZoomChange 프롭으로 확대를 프로그래밍 방식으로 제어할 수 있어요. 외부 버튼으로 확대/축소하고 싶을 때 유용해요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import { ZoomInIcon, ZoomOutIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

export const ControlledZoom = () => {
  const [zoom, setZoom] = useState(1)

  return (
    <div className={styles.Layout}>
      <div className={button.Group}>
        <button className={button.Root} onClick={() => setZoom(zoom - 0.1)}>
          <ZoomOutIcon />
        </button>
        <span style={{ fontSize: '0.875rem', minWidth: '3rem', textAlign: 'center' }}>{zoom.toFixed(1)}x</span>
        <button className={button.Root} onClick={() => setZoom(zoom + 0.1)}>
          <ZoomInIcon />
        </button>
      </div>

      <ImageCropper.Root className={styles.Root} zoom={zoom} onZoomChange={(e) => setZoom(e.zoom)}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

확대 한계 (Zoom Limits)

minZoom과 maxZoom을 설정해 사용자가 확대할 수 있는 범위를 제한해요. 과도한 확대나 이미지 경계를 벗어나는 축소를 방지해요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import { ZoomInIcon, ZoomOutIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

export const ZoomLimits = () => {
  const [zoom, setZoom] = useState(1)
  const minZoom = 0.5
  const maxZoom = 2

  return (
    <div className={styles.Layout}>
      <div className={button.Group}>
        <button className={button.Root} onClick={() => setZoom(Math.max(minZoom, zoom - 0.1))}>
          <ZoomOutIcon />
        </button>
        <span style={{ fontSize: '0.875rem', padding: '0 0.5rem', minWidth: '3rem', textAlign: 'center' }}>
          {zoom.toFixed(1)}x
        </span>
        <button className={button.Root} onClick={() => setZoom(Math.min(maxZoom, zoom + 0.1))}>
          <ZoomInIcon />
        </button>
      </div>

      <p className={styles.Description}>
        Zoom constrained between {minZoom}x and {maxZoom}x
      </p>

      <ImageCropper.Root
        className={styles.Root}
        zoom={zoom}
        onZoomChange={(e) => setZoom(e.zoom)}
        minZoom={minZoom}
        maxZoom={maxZoom}
      >
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

회전 (Rotation)

rotation과 onRotationChange 프롭으로 이미지를 회전해요. 값은 도(degree) 단위이며, 일반적인 증분은 90 또는 180이에요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import { RotateCcwIcon, RotateCwIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

export const Rotation = () => {
  const [rotation, setRotation] = useState(0)

  return (
    <div className={styles.Layout}>
      <div className={button.Group}>
        <button className={button.Root} onClick={() => setRotation(rotation - 90)}>
          <RotateCcwIcon />
        </button>
        <button className={button.Root} onClick={() => setRotation(rotation + 90)}>
          <RotateCwIcon />
        </button>
        <span style={{ fontSize: '0.875rem', padding: '0 0.5rem' }}>{rotation}°</span>
      </div>

      <ImageCropper.Root className={styles.Root} rotation={rotation} onRotationChange={(e) => setRotation(e.rotation)}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

뒤집기 (Flip)

flip 프롭으로 이미지를 가로 또는 세로로 뒤집어요. horizontal과 vertical 불리언을 가진 객체를 넘겨요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import { FlipHorizontalIcon, FlipVerticalIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

export const Flip = () => {
  const [flip, setFlip] = useState({ horizontal: false, vertical: false })

  return (
    <div className={styles.Layout}>
      <div className={button.Group}>
        <button
          className={button.Root}
          data-variant={flip.horizontal ? 'solid' : undefined}
          onClick={() => setFlip({ ...flip, horizontal: !flip.horizontal })}
        >
          <FlipHorizontalIcon />
          Horizontal
        </button>
        <button
          className={button.Root}
          data-variant={flip.vertical ? 'solid' : undefined}
          onClick={() => setFlip({ ...flip, vertical: !flip.vertical })}
        >
          <FlipVerticalIcon />
          Vertical
        </button>
      </div>

      <ImageCropper.Root className={styles.Root} flip={flip} onFlipChange={(e) => setFlip(e.flip)}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

최소·최대 크기 (Min and Max Size)

minWidth, minHeight, maxWidth, maxHeight로 크롭 영역의 크기를 제한해요. 선택 영역을 합리적인 범위 안에 유지해 줘요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import styles from 'styles/image-cropper.module.css'

export const MinMaxSize = () => {
  return (
    <div className={styles.Layout}>
      <p className={styles.Description}>Crop area constrained to min 80px and max 200px</p>

      <ImageCropper.Root className={styles.Root} minWidth={80} minHeight={80} maxWidth={200} maxHeight={200}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

고정 크롭 영역 (Fixed Crop Area)

이미지가 아래에서 움직이는 동안 크롭 영역이 고정되어야 할 때 fixedCropArea를 true로 설정해요. 오버레이 스타일 크롭에 유용해요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import styles from 'styles/image-cropper.module.css'

export const Fixed = () => {
  return (
    <div className={styles.Layout}>
      <ImageCropper.Root className={styles.Root} fixedCropArea>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

크롭 미리보기 (Crop Preview)

컨텍스트의 getCroppedImage()로 크롭 결과를 가져와요. { output: 'dataUrl' }과 함께 호출하면 img src에서 사용할 수 있는 base64 문자열을 반환해요.

import { ImageCropper, useImageCropper } from '@ark-ui/react/image-cropper'
import { CropIcon } from 'lucide-react'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

export const CropPreview = () => {
  const imageCropper = useImageCropper()
  const [preview, setPreview] = useState<string | null>(null)

  const handleCrop = async () => {
    const result = await imageCropper.getCroppedImage({ output: 'dataUrl' })
    if (typeof result === 'string') {
      setPreview(result)
    }
  }

  return (
    <div className={styles.Layout}>
      <div className={button.Group}>
        <button className={button.Root} data-variant="solid" onClick={handleCrop}>
          <CropIcon />
          Crop Image
        </button>
      </div>

      <ImageCropper.RootProvider className={styles.Root} value={imageCropper}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
            crossOrigin="anonymous"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.RootProvider>

      <div className={styles.Preview}>
        <span className={styles.PreviewLabel}>Preview</span>
        {preview && <img src={preview} alt="Cropped preview" className={styles.PreviewImage} />}
      </div>
    </div>
  )
}

초기화 (Reset)

컨텍스트는 이미지를 초기 상태로 복원하는 reset() 메서드를 노출해요. "실행 취소" 또는 "처음부터 시작" 버튼에 유용해요.

import { ImageCropper, useImageCropper } from '@ark-ui/react/image-cropper'
import { FlipHorizontalIcon, RotateCwIcon, RotateCcwIcon, RefreshCwIcon, ZoomInIcon, ZoomOutIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

export const Reset = () => {
  const imageCropper = useImageCropper()

  return (
    <div className={styles.Layout}>
      <div className={button.Group}>
        <button className={button.Root} onClick={() => imageCropper.zoomBy(-0.1)}>
          <ZoomOutIcon />
        </button>
        <button className={button.Root} onClick={() => imageCropper.zoomBy(0.1)}>
          <ZoomInIcon />
        </button>
        <button className={button.Root} onClick={() => imageCropper.rotateBy(-90)}>
          <RotateCcwIcon />
        </button>
        <button className={button.Root} onClick={() => imageCropper.rotateBy(90)}>
          <RotateCwIcon />
        </button>
        <button className={button.Root} onClick={() => imageCropper.flipHorizontally()}>
          <FlipHorizontalIcon />
        </button>
        <button className={button.Root} data-variant="surface" onClick={() => imageCropper.reset()}>
          <RefreshCwIcon />
          Reset
        </button>
      </div>

      <ImageCropper.RootProvider className={styles.Root} value={imageCropper}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.RootProvider>
    </div>
  )
}

이벤트 (Events)

onCropChange와 onZoomChange를 들어 크롭 위치와 확대 레벨을 추적해요. 외부 상태와 동기화하거나 실시간 미리보기를 보여 줄 때 사용해요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import { useState } from 'react'
import styles from 'styles/image-cropper.module.css'

export const Events = () => {
  const [cropData, setCropData] = useState({ x: 0, y: 0, width: 0, height: 0 })
  const [zoom, setZoom] = useState(1)

  return (
    <div className={styles.Layout}>
      <ImageCropper.Root
        className={styles.Root}
        onCropChange={(e) => setCropData(e.crop)}
        onZoomChange={(e) => setZoom(e.zoom)}
      >
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>

      <div className={styles.DataDisplay}>
        <div className={styles.DataItem}>
          <span className={styles.DataLabel}>Zoom</span>
          <span className={styles.DataValue}>{zoom.toFixed(2)}x</span>
        </div>
        <div className={styles.DataItem}>
          <span className={styles.DataLabel}>Position</span>
          <span className={styles.DataValue}>
            {Math.round(cropData.x)}, {Math.round(cropData.y)}
          </span>
        </div>
        <div className={styles.DataItem}>
          <span className={styles.DataLabel}>Size</span>
          <span className={styles.DataValue}>
            {Math.round(cropData.width)} × {Math.round(cropData.height)}
          </span>
        </div>
      </div>
    </div>
  )
}

컨텍스트 (Context)

루트 안 어디에서든 ImageCropper.Context를 사용해 크로퍼 API에 접근할 수 있어요. zoomBy, rotateBy, setZoom 같은 메서드를 얻을 수 있어요.

import { ImageCropper } from '@ark-ui/react/image-cropper'
import { ZoomInIcon, ZoomOutIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

export const Context = () => {
  return (
    <div className={styles.Layout}>
      <ImageCropper.Root className={styles.Root}>
        <ImageCropper.Context>
          {(context) => (
            <div className={button.Group}>
              <button className={button.Root} onClick={() => context.zoomBy(-0.1)}>
                <ZoomOutIcon />
              </button>
              <span style={{ fontSize: '0.875rem', padding: '0 0.5rem', minWidth: '3rem', textAlign: 'center' }}>
                {context.zoom.toFixed(1)}x
              </span>
              <button className={button.Root} onClick={() => context.zoomBy(0.1)}>
                <ZoomInIcon />
              </button>
            </div>
          )}
        </ImageCropper.Context>

        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.Root>
    </div>
  )
}

루트 프로바이더 (Root Provider)

컴포넌트 트리 밖에서 크로퍼를 제어해야 할 때 RootProvider와 useImageCropper를 사용해요. 커스텀 툴바를 만들거나 폼 상태와 통합할 수 있어요.

import { ImageCropper, useImageCropper } from '@ark-ui/react/image-cropper'
import { ZoomInIcon, ZoomOutIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/image-cropper.module.css'

export const RootProvider = () => {
  const imageCropper = useImageCropper()

  return (
    <div className={styles.Layout}>
      <div className={button.Group}>
        <button className={button.Root} onClick={() => imageCropper.setZoom(imageCropper.zoom - 0.1)}>
          <ZoomOutIcon />
        </button>
        <span style={{ fontSize: '0.875rem', minWidth: '3rem', textAlign: 'center' }}>
          {imageCropper.zoom.toFixed(1)}x
        </span>
        <button className={button.Root} onClick={() => imageCropper.setZoom(imageCropper.zoom + 0.1)}>
          <ZoomInIcon />
        </button>
      </div>

      <ImageCropper.RootProvider className={styles.Root} value={imageCropper}>
        <ImageCropper.Viewport className={styles.Viewport}>
          <ImageCropper.Image
            className={styles.Image}
            src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800"
            alt="Sample"
          />
          <ImageCropper.Selection className={styles.Selection}>
            {ImageCropper.handles.map((position) => (
              <ImageCropper.Handle className={styles.Handle} key={position} position={position}>
                <div />
              </ImageCropper.Handle>
            ))}
            <ImageCropper.Grid className={styles.Grid} axis="horizontal" />
            <ImageCropper.Grid className={styles.Grid} axis="vertical" />
          </ImageCropper.Selection>
        </ImageCropper.Viewport>
      </ImageCropper.RootProvider>
    </div>
  )
}

API 참조 (API Reference)

프롭 (Props)

Root

프롭 (Props)

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 프롭과 동작을 결합해요.

aspectRatio Type: number Required: false Default Value: undefined Description: 크롭 영역에 유지할 종횡비예요 (width / height). 예를 들어 16 / 9의 종횡비는 width 대 height 비율을 16:9로 유지해요. 제공되지 않으면 크롭 영역을 자유롭게 크기 조절할 수 있어요.

cropShape Type: 'circle' | 'rectangle' Required: false Default Value: "rectangle" Description: 크롭 영역의 모양이에요.

defaultFlip Type: FlipState Required: false Default Value: { horizontal: false, vertical: false } Description: 이미지에 적용할 초기 뒤집기 상태예요.

defaultRotation Type: number Required: false Default Value: 0 Description: 이미지에 적용할 초기 회전이에요. 도 단위예요.

defaultZoom Type: number Required: false Default Value: 1 Description: 이미지에 적용할 초기 확대 배율이에요.

fixedCropArea Type: boolean Required: false Default Value: false Description: 크롭 영역의 크기와 위치가 고정되어 있는지 여부예요.

flip Type: FlipState Required: false Default Value: undefined Description: 이미지의 제어된 뒤집기 상태예요.

ids Type: Partial<{ root: string viewport: string image: string selection: string handle: (position: string) => string }> Required: false Default Value: undefined Description: image cropper 요소들의 id예요.

initialCrop Type: Rect Required: false Default Value: undefined Description: 크롭 영역의 초기 사각형이에요. 제공되지 않으면 뷰포트 크기와 종횡비를 기반으로 스마트 기본값을 계산해요.

maxHeight Type: number Required: false Default Value: Infinity Description: 크롭 영역의 최대 높이예요.

maxWidth Type: number Required: false Default Value: Infinity Description: 크롭 영역의 최대 너비예요.

maxZoom Type: number Required: false Default Value: 5 Description: 허용되는 최대 확대 배율이에요.

minHeight Type: number Required: false Default Value: 40 Description: 크롭 영역의 최소 높이예요.

minWidth Type: number Required: false Default Value: 40 Description: 크롭 영역의 최소 너비예요.

minZoom Type: number Required: false Default Value: 1 Description: 허용되는 최소 확대 배율이에요.

nudgeStep Type: number Required: false Default Value: 1 Description: 키보드 화살표 키를 위한 기본 nudge 단계예요 (픽셀 단위).

nudgeStepCtrl Type: number Required: false Default Value: 50 Description: Ctrl/Cmd 키를 누르고 있을 때의 nudge 단계예요 (픽셀 단위).

nudgeStepShift Type: number Required: false Default Value: 10 Description: Shift 키를 누르고 있을 때의 nudge 단계예요 (픽셀 단위).

onCropChange Type: (details: CropChangeDetails) => void Required: false Default Value: undefined Description: 크롭 영역이 변경될 때 호출되는 콜백이에요.

onFlipChange Type: (details: FlipChangeDetails) => void Required: false Default Value: undefined Description: 뒤집기 상태가 변경될 때 호출되는 콜백이에요.

onRotationChange Type: (details: RotationChangeDetails) => void Required: false Default Value: undefined Description: 회전이 변경될 때 호출되는 콜백이에요.

onZoomChange Type: (details: ZoomChangeDetails) => void Required: false Default Value: undefined Description: 확대 레벨이 변경될 때 호출되는 콜백이에요.

rotation Type: number Required: false Default Value: undefined Description: 이미지의 제어된 회전이에요. 도 단위 (0 - 360).

translations Type: IntlTranslations Required: false Default Value: undefined Description: 접근성 요소와 그 상태를 식별하는 지역화된 문자열을 지정해요.

zoom Type: number Required: false Default Value: undefined Description: 이미지의 제어된 확대 레벨이에요.

zoomSensitivity Type: number Required: false Default Value: 2 Description: 핀치투줌이 얼마나 반응적인지 제어해요.

zoomStep Type: number Required: false Default Value: 0.1 Description: 휠 스텝당 적용되는 확대량이에요.

데이터 속성 (Data Attributes)

data-scope: image-cropper data-part: root data-fixed: data-shape: data-pinch: data-dragging: 드래깅 상태일 때 존재 data-panning:

Grid

프롭 (Props)

axis Type: 'horizontal' | 'vertical' Required: true Default Value: undefined Description: 표시할 그리드 선의 축이에요.

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 프롭과 동작을 결합해요.

데이터 속성 (Data Attributes)

data-scope: image-cropper data-part: grid data-axis: 리사이즈할 축 data-dragging: 드래깅 상태일 때 존재 data-panning:

Handle

프롭 (Props)

position Type: HandlePosition Required: true Default Value: undefined Description: 핸들의 위치예요.

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 프롭과 동작을 결합해요.

데이터 속성 (Data Attributes)

data-scope: image-cropper data-part: handle data-position: data-disabled: 비활성화될 때 존재

Image

프롭 (Props)

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 프롭과 동작을 결합해요.

데이터 속성 (Data Attributes)

data-scope: image-cropper data-part: image data-ready: data-flip-horizontal: data-flip-vertical:

RootProvider

프롭 (Props)

value Type: UseImageCropperReturn Required: true Default Value: undefined Description: undefined

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 프롭과 동작을 결합해요.

Selection

프롭 (Props)

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 프롭과 동작을 결합해요.

데이터 속성 (Data Attributes)

data-scope: image-cropper data-part: selection data-disabled: 비활성화될 때 존재 data-shape: data-measured: data-dragging: 드래깅 상태일 때 존재 data-panning:

Viewport

프롭 (Props)

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하고, 그 프롭과 동작을 결합해요.

데이터 속성 (Data Attributes)

data-scope: image-cropper data-part: viewport data-disabled: 비활성화될 때 존재

Context

API:

Property Type Description
zoom number 이미지의 현재 확대 레벨.
rotation number 이미지의 현재 회전. 도 단위.
flip FlipState 이미지의 현재 뒤집기 상태.
crop Rect 뷰포트 좌표에서의 현재 크롭 영역 사각형.
offset Point 이미지의 현재 오프셋(팬 위치).
naturalSize Size 이미지의 원본(자연) 크기.
viewportRect BoundingRect 뷰포트 사각형의 크기와 위치.
dragging boolean 크롭 영역이 현재 드래그되고 있는지 여부.
panning boolean 이미지가 현재 팬되고 있는지 여부.
setZoom (zoom: number) => void 이미지의 확대 레벨을 설정하는 함수.
zoomBy (delta: number) => void 상대량만큼 이미지를 확대하는 함수.
setRotation (rotation: number) => void 이미지의 회전을 설정하는 함수.
rotateBy (degrees: number) => void 상대량(도)만큼 이미지를 회전하는 함수.
setFlip (flip: Partial<FlipState>) => void 이미지의 뒤집기 상태를 설정하는 함수.
flipHorizontally (value?: boolean) => void 이미지를 가로로 뒤집는 함수. 불리언을 넘기면 명시적으로 설정하고, 생략하면 토글해요.
flipVertically (value?: boolean) => void 이미지를 세로로 뒤집는 함수. 불리언을 넘기면 명시적으로 설정하고, 생략하면 토글해요.
resize (handlePosition: HandlePosition, delta: number) => void 핸들에서 크롭 영역을 프로그래밍 방식으로 리사이즈하는 함수.
reset () => void 크로퍼를 초기 상태로 리셋하는 함수.
getCroppedImage `(options?: GetCroppedImageOptions) => Promise<Blob string
Blob 또는 data URL 중 하나로 해석되는 Promise를 반환해요.
getCropData () => CropData 원본 이미지 픽셀 단위로 크롭 기하(geometry)를 가져오는 함수.
rect는 축 정렬(axis-aligned)이며, corners는 정확한 원본 소스 사각형을 보존해요.

더 알아보기 (Learn more)