Skip to content

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

Components

Free

Image Cropper for Svelte UI SDK

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

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.

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

<script lang="ts">
import {
  ImageCropper, ImageCropperImage, ImageCropperSelection,
} from "@/components/ui/image-cropper";
</script>

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

<ImageCropper class="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 root is a group named Image cropper, which an aria-label on ImageCropper replaces, and the photo's alt is read inside it. The selection is a focusable slider named Crop, described as a crop area, and a screen reader hears its size and place in the photo's own pixels as it moves, such as 480 by 320 pixels, at 60, 40. Each of the eight handles is a slider of its own after it in the tab order, named for its edge or corner, such as Top edge. With fixedCropArea the handles are gone and the arrow keys pan the photo. The words are English, and an aria-label on ImageCropperSelection renames the selection.

Tab
Moves focus to the selection, then to each handle in turn: the top, right, bottom and left edges, then the four corners.
Arrow Up
Moves the selection up by about one pixel of the screen. On a handle that has a top or bottom edge, moves that edge instead, which grows or shrinks the crop.
Arrow Down
Moves the selection down by about one pixel of the screen. On a handle that has a top or bottom edge, moves that edge instead.
Arrow Left
Moves the selection left by about one pixel of the screen. On a handle that has a left or right edge, moves that edge instead.
Arrow Right
Moves the selection right by about one pixel of the screen. On a handle that has a left or right edge, moves that edge instead.
Shift+Arrow Up
Moves the selection, or the handle's edge, ten times as far. The same goes for the other arrows.
+
Zooms in about the crop's middle. The = key does the same on keyboards where both symbols share a key.
-
Zooms out about the crop's middle. The _ key does the same on keyboards where both symbols share a key.
R
Turns the photo a quarter clockwise.
Shift+R
Turns the photo a quarter counterclockwise.
Escape
During a drag, puts the crop back where the drag started.

Demos

Export the crop

The cropper's state 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 unless you pass an aspectRatio of your own, which is the shape a round avatar needs. The export follows the circle: getCroppedImage returns the square around it with its corners left transparent, which a PNG or WebP keeps and a JPEG fills with black.

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 plus and minus keys or a handle change it. At 1 the selection covers the whole photo, and zooming in shrinks it about its middle. The buttons step the level by a quarter and stop at 1 and at the 3 that maxZoom allows, so state and photo agree.

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, a pinch and the plus and minus keys zoom it.

Preview width

Initial crop

initialCrop places the first box at an x of 100 and a y of 80, 200 by 150 pixels, in the photo's own pixels, measured from its top-left corner. Use it to reopen a crop someone saved earlier: it lands on the same part of the picture whatever the size of the frame.

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 photo, so it starts at that maximum. Every value is in the photo's own pixels. Without them the floor is a single pixel and there is no ceiling.

Preview width

Zoom limits

maxZoom at 2 stops zooming in once the selection is half the photo's width and height, in place of the default of 10. minZoom at 0.5 is there for the other bases' markup and changes nothing: zoom 1, the selection over the whole photo, is as far out as it goes. 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 it 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 CORS headers from its server: the export loads it again with crossOrigin set to anonymous, and without them its promise rejects.

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 holds one to one unless you set a ratio of your own.

Without aspectRatio the box resizes freely, and holding Shift while dragging a handle keeps its current shape.

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

Pass onCropChange, which receives the crop as its first argument, with its x, y, width and height, and the change's details, with its reason, as its second, each time the box moves. onCropCommit takes the same arguments once a drag or a key press ends, which suits saving.

Those are pixels of the photo itself, measured from the top-left corner of the picture as it shows once turned and flipped, and the crop carries its rotation, flipX and flipY too, so a server can cut the original with it as it is. initialCrop takes the same shape to restore a saved box, as the Initial crop demo does.

How do I control Image Cropper zoom in Svelte?

Bind the level with bind:zoom, or pass zoom and update it in onZoomChange, which receives the new level, as the Controlled zoom demo does. Your own buttons then share one number with the plus and minus keys and the handles, and with fixedCropArea with the wheel and a pinch too.

Zoom 1 is the largest crop the photo allows, and zooming in shrinks the crop about its middle, up to maxZoom, 10 unless you set it, while minZoom changes nothing. Plus multiplies the level by 1.25 and minus divides it by the same. Clamp your buttons to that range: past a limit no change is reported, and your state drifts from the photo.

Why does my photo look stretched in the Image Cropper?

It shouldn't, because the cropper sizes the photo itself at its own proportions. A class on ImageCropper that fixes the frame's shape, such as aspect-video or a height, fits the whole photo inside the frame with empty bands beside it, and the crop stays in the photo's own pixels, so the export keeps its shape.

Remove that class and the frame takes the photo's own proportions once it loads, with no bands. If the layout needs a fixed shape, give it the ratio of the files people upload.

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?

Call rotateBy on the cropper's API with 90 or -90 to turn the photo a quarter, and flipHorizontally or flipVertically to mirror it, from your buttons through useImageCropperContext inside the cropper or useImageCropper outside it. R turns the photo from the keyboard, and Shift with R turns it back. The API reads both back as rotation and flip, and the crop turns and mirrors with the photo, so it keeps the same part of the picture.

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 1 unless you set them and there is no maximum, and the first box is fitted into the range, as the Min max size demo shows.

The limits are in the photo's own pixels, so a minimum is also the smallest the exported file gets at full size. To fix the size entirely, add fixedCropArea: the box stays put and people pan and zoom the photo under it.

API Reference

ImageCropper

PropType
crop?ImageCrop

The crop, in the image's own pixels, from the top left of the image as it shows once turned and flipped, with its rotation, flipX and flipY. Pass it straight to cropImage. Pass it to control the cropper. Two-way with bind:crop.

defaultCrop?ImageCrop

The crop at first, when uncontrolled.

Default
once the image loads, a crop at `aspectRatio` in the middle: four fifths of the largest in a box, the largest in a frame
onCropChange?(crop: Required<ImageCrop>, details: ImageCropperCropChangeDetails) → void

Runs while the crop changes: on every step of a drag, a key or the wheel, and once an image loads. details.cancel() stops it.

Type
(crop: Required<ImageCrop>, details: ImageCropperCropChangeDetails) → void
Parameters

crop – Required<ImageCrop>

details – ImageCropperCropChangeDetails

Returns
void
zoom?number

The zoom, where 1 is the largest crop the image allows. Pass it to control the zoom. Two-way with bind:zoom.

defaultZoom?number

The zoom once the image loads, when uncontrolled.

Default
1
onZoomChange?(details: { zoom: number }) → void

Runs when the zoom changes, by any means: keys, the wheel, a handle, zoom.

Type
(details: { zoom: number }) → void
Parameters

details – { zoom: number }

Returns
void
aspectRatio?number

Keeps the crop's width over its height, like 1 for a square or 16 / 9. Changing it fits the crop to the new ratio.

controller?ImageCropperController

Sets the crop from anywhere. Create one with createImageCropperController().

cropShape?ImageCropperShape

The other bases' name for shape.

Default
"rectangle"
debug?boolean

Logs every state change with its reason to the console, in development builds.

disabled?boolean

Stops every change: the selection can't be focused, and the buttons and zoom are disabled.

fixedCropArea?boolean

Keeps the selection still and pans and zooms the image under it: UI SDK's mode="frame".

Default
false
initialCrop?ImageCrop

The other bases' name for defaultCrop, in the image's own pixels.

maxHeight?number

The tallest the crop gets, in image pixels.

Default
Infinity
maxWidth?number

The widest the crop gets, in image pixels.

Default
Infinity
maxZoom?number

How far the crop magnifies the image, where 1 is the largest crop the image allows.

Default
10
minHeight?number

The shortest the crop gets, in image pixels.

Default
1
minWidth?number

The narrowest the crop gets, in image pixels.

Default
1
minZoom?number

Accepted for the other bases' markup. UI SDK's zoom starts at 1, the largest crop.

Default
1
mode?ImageCropperMode

"box" moves and resizes a selection over the whole image. "frame" keeps the selection still and as large as it fits, and pans and zooms the image under it, like an avatar editor.

Default
"box"
onCropCommit?(crop: Required<ImageCrop>, details: ImageCropperCropCommitDetails) → void

Runs once an interaction that changed the crop ends: the pointer lifts, a key is pressed, the wheel pauses. For saving.

Type
(crop: Required<ImageCrop>, details: ImageCropperCropCommitDetails) → void
Parameters

crop – Required<ImageCrop>

details – ImageCropperCropCommitDetails

Returns
void
shape?ImageCropperShape

The selection's shape, as data-shape. A circle is still a box to the crop, so pass shape: "circle" to cropImage too.

Default
"rectangle"
src?string

The image's URL, like an object URL for a file someone picked.

render?Snippet<[{ props, state, children }]>

Renders your own element: a snippet that gets the part's props to spread on it, its state, and children, its content.

Type
Snippet<[{ props, state, children }]>
class?string

Merged with the part's classes.

ImageCropperRootProvider

PropType
crop?ImageCrop

The crop, in the image's own pixels, from the top left of the image as it shows once turned and flipped, with its rotation, flipX and flipY. Pass it straight to cropImage. Pass it to control the cropper. Two-way with bind:crop.

defaultCrop?ImageCrop

The crop at first, when uncontrolled.

Default
once the image loads, a crop at `aspectRatio` in the middle: four fifths of the largest in a box, the largest in a frame
onCropChange?(crop: Required<ImageCrop>, details: ImageCropperCropChangeDetails) → void

Runs while the crop changes: on every step of a drag, a key or the wheel, and once an image loads. details.cancel() stops it.

Type
(crop: Required<ImageCrop>, details: ImageCropperCropChangeDetails) → void
Parameters

crop – Required<ImageCrop>

details – ImageCropperCropChangeDetails

Returns
void
valueUseImageCropperReturn

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

aspectRatio?number

Keeps the crop's width over its height, like 1 for a square or 16 / 9. Changing it fits the crop to the new ratio.

controller?ImageCropperController

Sets the crop from anywhere. Create one with createImageCropperController().

debug?boolean

Logs every state change with its reason to the console, in development builds.

disabled?boolean

Stops every change: the selection can't be focused, and the buttons and zoom are disabled.

maxZoom?number

How far the crop magnifies the image, where 1 is the largest crop the image allows.

Default
10
minHeight?number

The shortest the crop gets, in image pixels.

Default
1
minWidth?number

The narrowest the crop gets, in image pixels.

Default
1
mode?ImageCropperMode

"box" moves and resizes a selection over the whole image. "frame" keeps the selection still and as large as it fits, and pans and zooms the image under it, like an avatar editor.

Default
"box"
onCropCommit?(crop: Required<ImageCrop>, details: ImageCropperCropCommitDetails) → void

Runs once an interaction that changed the crop ends: the pointer lifts, a key is pressed, the wheel pauses. For saving.

Type
(crop: Required<ImageCrop>, details: ImageCropperCropCommitDetails) → void
Parameters

crop – Required<ImageCrop>

details – ImageCropperCropCommitDetails

Returns
void
shape?ImageCropperShape

The selection's shape, as data-shape. A circle is still a box to the crop, so pass shape: "circle" to cropImage too.

Default
"rectangle"
src?string

The image's URL, like an object URL for a file someone picked.

render?Snippet<[{ props, state, children }]>

Renders your own element: a snippet that gets the part's props to spread on it, its state, and children, its content.

Type
Snippet<[{ props, state, children }]>
class?string

Merged with the part's classes.

ImageCropperImage

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

PropType
src?string

The photo's URL. UI SDK reads it from the root, which takes it from here.

render?Snippet<[{ props, state, children }]>

Renders your own element: a snippet that gets the part's props to spread on it, its state, and children, its content.

Type
Snippet<[{ props, state, children }]>
class?string

Merged with the part's classes.

AttributeType
data-disabled?string

Present when the cropper is disabled.

data-error?string

Present when the image failed to load.

data-loading?string

Present until the image loads, while nothing can change.

data-mode"box" | "frame"

How the crop changes.

Type
"box" | "frame"
data-shape"rectangle" | "circle"

The selection's shape.

Type
"rectangle" | "circle"

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"
render?Snippet<[{ props, state, children }]>

Renders your own element: a snippet that gets the part's props to spread on it, its state, and children, its content.

Type
Snippet<[{ props, state, children }]>
class?string

Merged with the part's classes.

AttributeType
data-disabled?string

Present when the cropper is disabled.

data-dragging?string

Present while a pointer drags the selection, the image or, on a handle, that handle. Show the grid with it.

data-error?string

Present when the image failed to load.

data-loading?string

Present until the image loads, while nothing can change.

data-mode"box" | "frame"

How the crop changes.

Type
"box" | "frame"
data-shape"rectangle" | "circle"

The selection's shape.

Type
"rectangle" | "circle"
CSS variableType
--cropper-accentstring

ImageCropperHandle

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

PropType
positionImageCropperHandlePosition

The edge or corner it resizes, like "nw" for the top left corner.

render?Snippet<[{ props, state, children }]>

Renders your own element: a snippet that gets the part's props to spread on it, its state, and children, its content.

Type
Snippet<[{ props, state, children }]>
class?string

Merged with the part's classes.

AttributeType
data-disabled?string

Present when the cropper is disabled.

data-dragging?string

Present while a pointer drags the selection, the image or, on a handle, that handle. Show the grid with it.

data-error?string

Present when the image failed to load.

data-loading?string

Present until the image loads, while nothing can change.

data-mode"box" | "frame"

How the crop changes.

Type
"box" | "frame"
data-position"n" | "e" | "s" | "w" | "ne" | "nw" | "se" | "sw"

The edge or corner the handle resizes.

Type
"n" | "e" | "s" | "w" | "ne" | "nw" | "se" | "sw"
data-shape"rectangle" | "circle"

The selection's shape.

Type
"rectangle" | "circle"
CSS variableType
--cropper-accentstring
--cropper-handler-sizestring
--cropper-handler-widthstring

ImageCropperGrid

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

PropType
axis"horizontal" | "vertical"

The lines it draws: across the selection, or up it.

Type
"horizontal" | "vertical"
render?Snippet<[{ props, state, children }]>

Renders your own element: a snippet that gets the part's props to spread on it, its state, and children, its content.

Type
Snippet<[{ props, state, children }]>
class?string

Merged with the part's classes.

AttributeType
data-axis?string

Mirrors axis.

data-disabled?string

Present when the cropper is disabled.

data-dragging?string

Present while a pointer drags the selection, the image or, on a handle, that handle. Show the grid with it.

data-error?string

Present when the image failed to load.

data-loading?string

Present until the image loads, while nothing can change.

data-mode"box" | "frame"

How the crop changes.

Type
"box" | "frame"
data-shape"rectangle" | "circle"

The selection's shape.

Type
"rectangle" | "circle"

useImageCropper

PropType
zoom?number

The zoom, where 1 is the largest crop the image allows. Pass it to control the zoom. Two-way with bind:zoom.

defaultZoom?number

The zoom once the image loads, when uncontrolled.

onZoomChange?(details: { zoom: number }) → void

Runs when the zoom changes, by any means: keys, the wheel, a handle, zoom.

Type
(details: { zoom: number }) → void
Parameters

details – { zoom: number }

Returns
void
cropShape?ImageCropperShape

The other bases' name for shape.

fixedCropArea?boolean

Keeps the selection still and pans and zooms the image under it: UI SDK's mode="frame".

initialCrop?ImageCrop

The other bases' name for defaultCrop, in the image's own pixels.

maxHeight?number

The tallest the crop gets, in image pixels.

maxWidth?number

The widest the crop gets, in image pixels.

minZoom?number

Accepted for the other bases' markup. UI SDK's zoom starts at 1, the largest crop.

ImageCropperContext