react-image-crop

repository·master·Indexed 26 days ago

https://github.com/dominictobias/react-image-crop

A lightweight, dependency-free, and responsive image cropping tool for React applications. It supports touch interaction, fixed aspect ratios, and cropping in either pixels or percentages. The library provides the ReactCrop component along with utility functions like cropToCanvas, cropToImg, makeAspectCrop, and centerCrop to handle image processing and preview generation.

Tokens
3.6K
Snippets
7
Records
24
Agent score
87%

What's inside react-image-crop

  1. Center an aspect ratio crop

    master

    To center a crop with a specific aspect ratio, use the makeAspectCrop and centerCrop helper functions. You should listen to the onLoad event of the image to obtain its natural dimensions before calculating the crop.

    // 1. Listen to the load event
    <ReactCrop crop={crop} aspect={16 / 9}>
      <img src={src} onLoad={onImageLoad} />
    </ReactCrop>
    
    // 2. Use helpers to calculate the centered crop
    function onImageLoad(e) {
      const { naturalWidth: width, naturalHeight: height } = e.currentTarget
    
      const crop = centerCrop(
        makeAspectCrop(
          {
            unit: '%',
            width: 90,
          },
          16 / 9,
          width,
          height
        ),
        width,
        height
      )
    
      setCrop(crop)
    }
  2. Import ReactCrop and its styles

    master

    To use the component, import ReactCrop from the main module and include the required CSS or SCSS files in your project.

    import ReactCrop from 'react-image-crop'
    import 'react-image-crop/dist/ReactCrop.css'
    // or scss:
    // import 'react-image-crop/src/ReactCrop.scss'
  3. Generate a crop preview in the browser

    master

    Use cropToCanvas to render a completed crop to an existing <canvas> element, or cropToImg to get the crop as an image object URL. Both helpers accept optional scale and rotate arguments.

    import { useRef, useState } from 'react'
    import ReactCrop, { cropToCanvas, cropToImg, type Crop, type PixelCrop } from 'react-image-crop'
    
    function CropPreview({ src }: { src: string }) {
      const imgRef = useRef<HTMLImageElement>(null)
      const previewCanvasRef = useRef<HTMLCanvasElement>(null)
      const [crop, setCrop] = useState<Crop>()
      const [completedCrop, setCompletedCrop] = useState<PixelCrop>()
      const [previewSrc, setPreviewSrc] = useState('')
    
      async function updatePreview(crop: PixelCrop) {
        if (!imgRef.current || !previewCanvasRef.current) {
          return
        }
    
        await cropToCanvas(imgRef.current, previewCanvasRef.current, crop)
        setPreviewSrc(await cropToImg(imgRef.current, crop))
      }
    
      return (
        <>
          <ReactCrop
            crop={crop}
            onChange={(_, percentCrop) => setCrop(percentCrop)}
            onComplete={c => {
              setCompletedCrop(c)
              void updatePreview(c)
            }}
          >
            <img ref={imgRef} alt="Crop me" src={src} />
          </ReactCrop>
    
          {!!completedCrop && <canvas ref={previewCanvasRef} />}
          {!!previewSrc && <img alt="Crop preview" src={previewSrc} />}
        </>
      )
    }
  4. Use ReactCrop via CDN

    master

    If you are not using a package manager, you can include the library via CDN. When using the global <script> tag, access the component via ReactCrop.Component.

    <link href="https://unpkg.com/react-image-crop/dist/ReactCrop.css" rel="stylesheet" />
    <script src="https://unpkg.com/react-image-crop/dist/index.umd.cjs"></script>
  5. Use the ReactCrop component

    master

    The ReactCrop component is the primary interface for implementing image cropping. It wraps a media element (like an <img> or <video>) and provides a UI for selecting and resizing a crop area.

    To use it, pass your media element as children and provide a crop object and an onChange callback to manage the crop state.

  6. Use ReactCrop for basic image cropping

    master

    Wrap an <img> element with the ReactCrop component. You must manage the crop state and provide an onChange callback to update it, otherwise the UI will not respond to user interactions.

    import ReactCrop, { type Crop } from 'react-image-crop'
    
    function CropDemo({ src }) {
      const [crop, setCrop] = useState<Crop>()
      return (
        <ReactCrop crop={crop} onChange={c => setCrop(c)}>
          <img src={src} />
        </ReactCrop>
      )
    }
  7. Customize React Crop styles using CSS variables

    master

    You can customize the appearance of the ReactCrop component by overriding the following CSS custom properties defined in the :root scope:

    • --rc-drag-handle-size: Size of the drag handles (default: 12px).
    • --rc-drag-handle-mobile-size: Size of the drag handles on mobile devices (default: 24px).
    • --rc-drag-handle-bg-colour: Background color of the drag handles (default: rgba(0, 0, 0, 0.2)).
    • --rc-drag-bar-size: The invisible grip size of the crop selection edges (default: 6px).
    • --rc-border-color: Color of the crop selection border (default: rgba(255, 255, 255, 0.7)).
    • --rc-focus-color: Color used when a handle or the selection is focused (default: #0088ff).
  8. Configure ReactCropProps

    master

    The ReactCrop component accepts the following configuration props:

    PropTypeDescription
    cropCropRequired (since v10). The current crop state. Omit the object entirely if you don't want a crop.
    onChange(crop: PixelCrop, percentageCrop: PercentCrop) => voidRequired. Callback triggered on every crop change. You must update your state with the provided values and pass them back via the crop prop.
    aspectnumberThe aspect ratio of the crop (e.g., 1 for square, 16 / 9 for landscape).
    circularCropbooleanIf true, the crop area is shown as a circle (or oval if aspect is not 1).
    disabledbooleanIf true, the user cannot resize or draw a new crop. Adds ReactCrop--disabled class.
    lockedbooleanIf true, the user cannot create or resize, but can still drag the existing crop. Adds ReactCrop--locked class.
    keepSelectionbooleanIf true, selection cannot be disabled by clicking outside the area.
    minWidth / minHeightnumberMinimum dimensions for the crop in pixels.
    maxWidth / maxHeightnumberMaximum dimensions for the crop in pixels.
    ruleOfThirdsbooleanShows rule of thirds lines in the cropped area.
    onComplete(crop: PixelCrop, percentageCrop: PercentCrop) => voidCallback triggered after a resize, drag, or nudge is finished.
    onDragStart(e: PointerEvent) => voidCallback when a user starts dragging or resizing.
    onDragEnd(e: PointerEvent) => voidCallback when a user releases the cursor/touch.
    ariaLabelsobjectObject to override built-in English ARIA labels for accessibility.
    classNamestringCustom CSS class for the container.
    styleReact.CSSPropertiesInline styles for the container.
    renderSelectionAddon(state: ReactCropState) => React.ReactNodeFunction to render a custom element inside the crop selection.