Skip to content

shadcn.io is an independent project built on shadcn/ui

Components

Free

Image Cropper for Ark UI

A crop box over a photo that people drag, resize and zoom, with a locked aspect ratio or a circle for avatars. For React projects on Ark UI.

On this page9 sections

An image cropper lays a movable, resizable box over a photo, dims everything outside it, and lets people zoom and pan the picture underneath. Reach for it before an upload, when an avatar, a cover or a product shot has to fit a set shape.

It only marks the region: the file stays as it is until your code exports the crop. For a closer look at a picture with nothing saved, use Image Zoom.

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Anatomy

Image Cropper anatomy: root, image, selection, handle, grid

Usage

import {
  ImageCropper, ImageCropperImage, ImageCropperSelection,
} from "@/components/ui/image-cropper";

ImageCropperSelection draws the box with its grid and its eight handles, so these three parts are the whole cropper.

<ImageCropper className="max-w-lg">
  <ImageCropperImage
    alt="Crop me"
    src="https://images.unsplash.com/photo-1662692735672-544412d65934?w=600&auto=format"
  />
  <ImageCropperSelection />
</ImageCropper>

The frame fills the width it's given and takes the photo's own proportions once the photo loads, so it has no height before that.

Accessibility

The selection is a focusable slider labeled Crop selection area (rectangle), or (circle) for a round crop, and a screen reader hears its position and size as it moves, such as Position X 120px, Y 40px. Size 200px by 150px, with a hint about the keys below. The root is a group named Image cropper whose description reports the zoom and the crop, and the photo is hidden from assistive technology, so its alt is never read. The handles answer the pointer only. With fixedCropArea, the arrow keys pan the photo under the box and Alt with an arrow does nothing. The words are English, and translations replaces them.

Arrow Up
Moves the crop selection upward by the configured nudge step. Hold Shift for the nudgeStepShift value or Ctrl/Cmd for nudgeStepCtrl.
Arrow Down
Moves the crop selection downward by the configured nudge step. Hold Shift for the nudgeStepShift value or Ctrl/Cmd for nudgeStepCtrl.
Arrow Left
Moves the crop selection to the left by the configured nudge step. Hold Shift for the nudgeStepShift value or Ctrl/Cmd for nudgeStepCtrl.
Arrow Right
Moves the crop selection to the right by the configured nudge step. Hold Shift for the nudgeStepShift value or Ctrl/Cmd for nudgeStepCtrl.
Alt+Arrow Up
Resizes the crop vertically from the bottom handle, reducing the height. Hold Shift or Ctrl/Cmd for the larger nudge steps.
Alt+Arrow Down
Resizes the crop vertically from the bottom handle, increasing the height. Hold Shift or Ctrl/Cmd for the larger nudge steps.
Alt+Arrow Left
Resizes the crop horizontally from the right handle, reducing the width. Hold Shift or Ctrl/Cmd for the larger nudge steps.
Alt+Arrow Right
Resizes the crop horizontally from the right handle, increasing the width. Hold Shift or Ctrl/Cmd for the larger nudge steps.
+
Zooms in on the image. The = key performs the same action on keyboards where both symbols share a key.
-
Zooms out of the image. The _ key performs the same action on keyboards where both symbols share a key.
Tab
Moves focus to the crop selection, the cropper's one stop in the tab order.

Demos

Export the crop

The cropper's machine comes from useImageCropper and goes to ImageCropperRootProvider, so the Crop button outside it can call getCroppedImage. Here it asks for a data URL at most 256 pixels wide and shows it in a round preview. Leave output out to get a Blob for an upload instead.

Preview width

Aspect ratio

aspectRatio set to 16 / 9 keeps the box widescreen through every drag of a handle, and it starts 80 percent as wide as the frame. Lock the ratio when the crop fills a slot of known shape, such as a blog cover or a video poster. Leave it out and people can draw any rectangle.

Preview width

Circle crop

cropShape set to circle rounds the box and holds it at one to one, whatever aspectRatio says, which is the shape a round avatar needs. The circle is only the mask on screen: the image you export is the square around it, so show it in a round frame such as an Avatar or round its corners when you save it.

Preview width

Controlled zoom

The zoom level lives in the demo's state, passed in as zoom and updated from the zoom-change callback whenever the wheel, a pinch or the plus and minus keys move it. The two buttons under the photo step it by a quarter, and they stop at the same 1 and 3 that minZoom and maxZoom give the cropper, so the state and the photo never drift apart.

Preview width

Fixed crop area

fixedCropArea pins the box, hides its handles and turns every drag into a pan of the photo underneath, so people choose what lands in the frame instead of drawing it. Use it when the output shape is decided, such as a profile photo or a banner. The arrow keys pan the photo here too, and the wheel and the plus and minus keys still zoom.

Preview width

Initial crop

initialCrop places the first box at an x of 100 and a y of 80, 200 by 150 pixels, measured from the top-left corner of the frame on screen rather than in the photo's own pixels. Use it to reopen a crop someone saved earlier. It only lines up again when the frame is the same size as when it was saved.

Preview width

Min max size

minWidth and minHeight of 80, with maxWidth at 280 and maxHeight at 160, keep the box between a usable square and a size well inside the frame, so on a wide screen it starts at that maximum. Every value is in pixels on screen. Without them the floor is 40 by 40 and there is no ceiling.

Preview width

Zoom limits

minZoom at 0.5 and maxZoom at 2 let the photo shrink to half the frame and grow to twice its size, in place of the defaults of 1 and 5. Below 1 the frame shows empty space around the photo, which suits a picture that should fit whole inside the crop. Keep the maximum low when a deep zoom would export a crop too small to use.

Preview width

FAQ

How do I get the cropped image as a file from Image Cropper?

Call getCroppedImage on the cropper's API. It draws the selected region at the photo's own resolution onto a canvas and resolves to a PNG Blob, or to a data URL if you ask for one through output, and it takes type, quality and maxSize for a JPEG or WebP at a capped size.

To reach the API from a button outside the cropper, create the machine with useImageCropper and pass it as value to ImageCropperRootProvider in place of ImageCropper, as the Export the crop demo does. Inside the cropper, useImageCropperContext returns the same API. A photo from another origin needs crossOrigin set to anonymous and CORS headers from its server, or the canvas is blocked and the result is null.

How do I lock the aspect ratio of an Image Cropper?

Set aspectRatio on ImageCropper to width divided by height: 1 for a square, 16 / 9 for a widescreen cover, 4 / 5 for a portrait post. Every drag of a handle then keeps that shape, as the Aspect ratio demo shows, and cropShape set to circle always holds one to one.

Without aspectRatio the box resizes freely. Holding Shift while dragging a handle keeps its current shape, and holding Alt resizes it around its center.

How do I read the crop coordinates from an Image Cropper?

Pass onCropChange, which receives an object whose crop holds x, y, width and height each time the box moves.

Those are pixels of the frame on screen, measured from its top-left corner, and zooming or panning the photo doesn't change them. initialCrop takes the same shape to restore a saved box, as the Initial crop demo does. For the region in the photo's own pixels, which a server needs to crop the original, use getCropData from the cropper's API, which accounts for zoom, pan, rotation and flip.

How do I control Image Cropper zoom in React?

Hold the level in state, pass it as zoom and update it in onZoomChange, which receives an object whose zoom is the new level. Your own buttons then share one number with the wheel, a pinch and the plus and minus keys, as in the Controlled zoom demo.

The cropper keeps zoom between minZoom and maxZoom, 1 and 5 unless you set them, and moves it by zoomStep, 0.1, for each wheel event or key press. Clamp your buttons to the same range: a value past a limit is clamped, and when that leaves the zoom where it was, no change is reported and your state drifts from the photo.

Why does my photo look stretched in the Image Cropper?

A class on ImageCropper that fixes the frame's shape, such as aspect-video or a height, is the usual cause. The photo always fills the frame on both axes, because the cropper sets object-fit to fill inline, so a frame of other proportions stretches it.

Remove that class and the frame takes the photo's own proportions once it loads. If the layout needs a fixed shape, give it the ratio of the files people upload. A stretched frame also bends the export: a square drawn on screen comes out as a rectangle, since each axis maps back to the photo separately.

How do I crop a photo before uploading it with Image Cropper?

Take the chosen file from a File Upload or a file input, turn it into a URL with URL.createObjectURL, and pass that URL as src on ImageCropperImage. A local object URL counts as the page's own origin, so exporting the crop needs no CORS setup.

On submit, export the region with getCroppedImage and append the Blob to a FormData. Call URL.revokeObjectURL when the cropper goes away, so the browser can free the file.

How do I rotate or flip the image in Image Cropper?

Hold the angle in state and pass it as rotation, in degrees, such as 90 after a Rotate button is pressed, and pass flip as an object with horizontal and vertical set to true or false. Neither has controls of its own, so the buttons are yours. Use defaultRotation and defaultFlip instead when the cropper should only start that way.

The export follows both, so getCroppedImage returns the region turned and mirrored as it looks on screen.

How do I set a minimum or maximum crop size in Image Cropper?

Set minWidth, minHeight, maxWidth and maxHeight on ImageCropper. The minimums are 40 unless you set them and there is no maximum, and the first box is clamped into the range, as the Min max size demo shows.

The limits are pixels of the frame on screen, so they don't promise a resolution in the exported file. Check the size from getCropData when that matters. To fix the size entirely, add fixedCropArea: the box stays put and people pan and zoom the photo under it.

API Reference

ImageCropper

<div> data-slot="image-cropper"

PropType
flip?object

The controlled flip state of the image.

Type
{ horizontal: boolean; vertical: boolean }
defaultFlip?object

The initial flip state to apply to the image.

Type
{ horizontal: boolean; vertical: boolean }
Default
{ horizontal: false, vertical: false }
onFlipChange?(details: FlipChangeDetails) → void

Callback fired when the flip state changes.

Type
(details: FlipChangeDetails) → void
Parameters

details – { flip: FlipState }

Returns
void
rotation?number

The controlled rotation of the image in degrees (0 - 360).

defaultRotation?number

The initial rotation to apply to the image in degrees.

Default
0
onRotationChange?(details: RotationChangeDetails) → void

Callback fired when the rotation changes.

Type
(details: RotationChangeDetails) → void
Parameters

details – { rotation: number }

Returns
void
zoom?number

The controlled zoom level of the image.

defaultZoom?number

The initial zoom factor to apply to the image.

Default
1
onZoomChange?(details: ZoomChangeDetails) → void

Callback fired when the zoom level changes.

Type
(details: ZoomChangeDetails) → void
Parameters

details – { zoom: number }

Returns
void
aspectRatio?number

The aspect ratio to maintain for the crop area (width / height). For example, an aspect ratio of 16 / 9 will maintain a width to height ratio of 16:9. If not provided, the crop area can be freely resized.

cropShape?"rectangle" | "circle"

The shape of the crop area.

Type
"rectangle" | "circle"
Default
"rectangle"
dir?"ltr" | "rtl"

The document's text/writing direction.

Type
"ltr" | "rtl"
Default
"ltr"
fixedCropArea?boolean

Whether the crop area is fixed in size and position.

Default
false
id?string

The unique identifier of the machine.

ids?object

The ids of the image cropper elements.

Type
{ root?: string; viewport?: string; image?: string; selection?: string; handle?: (position: string) → string }
initialCrop?object

The initial rectangle of the crop area. If not provided, a smart default will be computed based on viewport size and aspect ratio.

Type
{ y: number; x: number }
maxHeight?number

The maximum height of the crop area.

Default
Infinity
maxWidth?number

The maximum width of the crop area.

Default
Infinity
maxZoom?number

The maximum zoom factor allowed.

Default
5
minHeight?number

The minimum height of the crop area.

Default
40
minWidth?number

The minimum width of the crop area.

Default
40
minZoom?number

The minimum zoom factor allowed.

Default
1
nudgeStep?number

The base nudge step for keyboard arrow keys (in pixels).

Default
1
nudgeStepCtrl?number

The nudge step when Ctrl/Cmd key is held (in pixels).

Default
50
nudgeStepShift?number

The nudge step when Shift key is held (in pixels).

Default
10
onCropChange?(details: CropChangeDetails) → void

Callback fired when the crop area changes.

Type
(details: CropChangeDetails) → void
Parameters

details – { crop: Rect }

Returns
void
translations?object

Specifies the localized strings that identify accessibility elements and their states.

Type
{ rootLabel?: string; rootRoleDescription?: string; previewLoading?: string; previewDescription?: (details: PreviewDescriptionDetails) → string; selectionLabel?: (details: SelectionLabelDetails) → string; selectionRoleDescription?: string; selectionInstructions?: string; selectionValueText?: (details: SelectionValueTextDetails) → string }
zoomSensitivity?number

Controls how responsive pinch-to-zoom is.

Default
2
zoomStep?number

The amount of zoom applied per wheel step.

Default
0.1
asChild?boolean

Use the provided child element as the default rendered element, combining their props and behavior.

className?string

Merged with the part's classes.

AttributeType
data-dragging?string

Present when in the dragging state.

data-fixed?string

Present when fixedCropArea is true.

data-panning?string

Present when panning is true.

data-pinch?string

Present when pinch.

data-shapestring

Mirrors cropShape.

CSS variableType
--crop-heightstring

The height of the Root.

--crop-widthstring

The width of the Root.

--crop-xstring

The crop x value for the Root.

--crop-ystring

The crop y value for the Root.

--image-offset-xstring

The offset position for image.

--image-offset-ystring

The offset position for image.

--image-rotationstring

The image rotation value for the Root.

--image-zoomstring

The image zoom value for the Root.

ImageCropperImage

<img> data-slot="image-cropper-image"

PropType
asChild?boolean

Use the provided child element as the default rendered element, combining their props and behavior.

className?string

Merged with the part's classes.

AttributeType
data-flip-horizontal?string

Present when flipHorizontal is true.

data-flip-vertical?string

Present when flipVertical is true.

data-ownedbystring

Id of the viewport part.

data-ready?string

Present when isImageReady is true.

ImageCropperSelection

<div> data-slot="image-cropper-selection"

PropType
axis?"horizontal" | "vertical" | "both"

The axis of the grid to show.

Type
"horizontal" | "vertical" | "both"
Default
"both"
asChild?boolean

Use the provided child element as the default rendered element, combining their props and behavior.

className?string

Merged with the part's classes.

AttributeType
data-disabled?string

Present when disabled.

data-dragging?string

Present when in the dragging state.

data-measured?string

Present when isMeasured is true.

data-panning?string

Present when panning is true.

data-shapestring

Mirrors cropShape.

CSS variableType
--cropper-accentstring

ImageCropperHandle

<div> data-slot="image-cropper-handle"

PropType
position"n" | "e" | "s" | "w" | "ne" | "se" | "sw" | "nw"

The position of the handle.

Type
"n" | "e" | "s" | "w" | "ne" | "se" | "sw" | "nw"
asChild?boolean

Use the provided child element as the default rendered element, combining their props and behavior.

className?string

Merged with the part's classes.

AttributeType
data-disabled?string

Present when disabled.

data-placement?string

The placement of the handle.

data-positionstring

Mirrors handlePosition.

CSS variableType
--cropper-accentstring
--cropper-handler-sizestring
--cropper-handler-widthstring

ImageCropperGrid

<div> data-slot="image-cropper-grid"

PropType
axis"horizontal" | "vertical"

The axis of the grid lines to display.

Type
"horizontal" | "vertical"
asChild?boolean

Use the provided child element as the default rendered element, combining their props and behavior.

className?string

Merged with the part's classes.

AttributeType
data-axisstring

The axis to resize.

data-dragging?string

Present when in the dragging state.

data-panning?string

Present when panning is true.

ImageCropperRootProvider

<div> data-slot="image-cropper"

PropType
valueUseImageCropperReturn

What useImageCropper() returns: the state and API, made outside the component to control it.

asChild?boolean

Use the provided child element as the default rendered element, combining their props and behavior.

className?string

Merged with the part's classes.

AttributeType
data-dragging?string

Present when dragging is true.

data-fixed?string

Present when fixedCropArea is true.

data-panning?string

Present when panning is true.

data-pinch?string

Present when pinch.

data-shapestring

Mirrors cropShape.

CSS variableType
--crop-heightstring
--crop-widthstring
--crop-xstring
--crop-ystring
--image-offset-xstring
--image-offset-ystring
--image-rotationstring
--image-zoomstring

useImageCropper

PropType
flip?object

The controlled flip state of the image.

Type
{ horizontal: boolean; vertical: boolean }
defaultFlip?object

The initial flip state to apply to the image.

Type
{ horizontal: boolean; vertical: boolean }
Default
{ horizontal: false, vertical: false }
onFlipChange?(details: FlipChangeDetails) → void

Callback fired when the flip state changes.

Type
(details: FlipChangeDetails) → void
Parameters

details – { flip: FlipState }

Returns
void
rotation?number

The controlled rotation of the image in degrees (0 - 360).

defaultRotation?number

The initial rotation to apply to the image in degrees.

Default
0
onRotationChange?(details: RotationChangeDetails) → void

Callback fired when the rotation changes.

Type
(details: RotationChangeDetails) → void
Parameters

details – { rotation: number }

Returns
void
zoom?number

The controlled zoom level of the image.

defaultZoom?number

The initial zoom factor to apply to the image.

Default
1
onZoomChange?(details: ZoomChangeDetails) → void

Callback fired when the zoom level changes.

Type
(details: ZoomChangeDetails) → void
Parameters

details – { zoom: number }

Returns
void
aspectRatio?number

The aspect ratio to maintain for the crop area (width / height). For example, an aspect ratio of 16 / 9 will maintain a width to height ratio of 16:9. If not provided, the crop area can be freely resized.

cropShape?"rectangle" | "circle"

The shape of the crop area.

Type
"rectangle" | "circle"
Default
"rectangle"
fixedCropArea?boolean

Whether the crop area is fixed in size and position.

Default
false
id?string

The unique identifier of the machine.

ids?object

The ids of the image cropper elements.

Type
{ root?: string; viewport?: string; image?: string; selection?: string; handle?: (position: string) → string }
initialCrop?object

The initial rectangle of the crop area. If not provided, a smart default will be computed based on viewport size and aspect ratio.

Type
{ y: number; x: number }
maxHeight?number

The maximum height of the crop area.

Default
Infinity
maxWidth?number

The maximum width of the crop area.

Default
Infinity
maxZoom?number

The maximum zoom factor allowed.

Default
5
minHeight?number

The minimum height of the crop area.

Default
40
minWidth?number

The minimum width of the crop area.

Default
40
minZoom?number

The minimum zoom factor allowed.

Default
1
nudgeStep?number

The base nudge step for keyboard arrow keys (in pixels).

Default
1
nudgeStepCtrl?number

The nudge step when Ctrl/Cmd key is held (in pixels).

Default
50
nudgeStepShift?number

The nudge step when Shift key is held (in pixels).

Default
10
onCropChange?(details: CropChangeDetails) → void

Callback fired when the crop area changes.

Type
(details: CropChangeDetails) → void
Parameters

details – { crop: Rect }

Returns
void
translations?object

Specifies the localized strings that identify accessibility elements and their states.

Type
{ rootLabel?: string; rootRoleDescription?: string; previewLoading?: string; previewDescription?: (details: PreviewDescriptionDetails) → string; selectionLabel?: (details: SelectionLabelDetails) → string; selectionRoleDescription?: string; selectionInstructions?: string; selectionValueText?: (details: SelectionValueTextDetails) → string }
zoomSensitivity?number

Controls how responsive pinch-to-zoom is.

Default
2
zoomStep?number

The amount of zoom applied per wheel step.

Default
0.1

ImageCropperContext

PropType
cropobject

The current crop area rectangle in viewport coordinates.

Type
{ y: number; x: number }
draggingboolean

Whether the crop area is currently being dragged.

flipobject

The current flip state of the image.

Type
{ horizontal: boolean; vertical: boolean }
flipHorizontally(value?: boolean) → void

Function to flip the image horizontally. Pass a boolean to set explicitly or omit to toggle.

Parameters

value? – boolean

Returns
void
flipVertically(value?: boolean) → void

Function to flip the image vertically. Pass a boolean to set explicitly or omit to toggle.

Parameters

value? – boolean

Returns
void
getCropData() → CropData

Function to get the crop geometry in natural image pixels. The rect is axis-aligned; corners preserves the exact source quad.

Returns
CropData
getCroppedImage(options?: GetCroppedImageOptions) → Promise<Blob | string | null>

Function to get the cropped image with all transformations applied. Returns a Promise that resolves to either a Blob or data URL.

Type
(options?: GetCroppedImageOptions) → Promise<Blob | string | null>
Parameters

options? – { type?: string; quality?: number; maxSize?: Size; output?: "blob" | "dataUrl" }

Returns
Promise<Blob | string | null>
naturalSizeobject

The natural (original) size of the image.

Type
{ width: number; height: number }
offsetobject

The current offset (pan position) of the image.

Type
{ x: number; y: number }
panningboolean

Whether the image is currently being panned.

reset() → void

Function to reset the cropper to its initial state.

Returns
void
resize(handlePosition: HandlePosition, delta: number) → void

Function to resize the crop area from a handle programmatically.

Type
(handlePosition: HandlePosition, delta: number) → void
Parameters

handlePosition – HandlePosition

delta – number

Returns
void
rotateBy(degrees: number) → void

Function to rotate the image by a relative amount in degrees.

Parameters

degrees – number

Returns
void
rotationnumber

The current rotation of the image in degrees.

setCrop(crop: Rect) → void

Function to set the crop area in viewport coordinates, constrained like initialCrop (min/max size, aspect ratio and viewport bounds). Zoom, rotation, flip and pan are kept. Does nothing when fixedCropArea is set or before the viewport is measured.

Parameters

crop – { y: number; x: number }

Returns
void
setFlip(flip: Partial<FlipState>) → void

Function to set the flip state of the image.

Type
(flip: Partial<FlipState>) → void
Parameters

flip – Partial<FlipState>

Returns
void
setRotation(rotation: number) → void

Function to set the rotation of the image.

Parameters

rotation – number

Returns
void
setZoom(zoom: number) → void

Function to set the zoom level of the image.

Parameters

zoom – number

Returns
void
viewportRectobject

The viewport rectangle dimensions and position.

Type
{ width: number; height: number; top: number; left: number; right: number; bottom: number }
zoomnumber

The current zoom level of the image.

zoomBy(delta: number) → void

Function to zoom the image by a relative amount.

Parameters

delta – number

Returns
void