Image Cropper

Pro

Crop, with the parts that silently corrupt the result handled: EXIF orientation, the browser's canvas ceiling, and a quality setting PNG ignores. An image cropper fails by producing a picture rather than an error, so it reports what the crop will actually produce rather than what was selected.

</>sv-image-cropper imagecropeditoravatarcanvas

Complexity tier: Interactive The primitive bar, plus: its async states are declared — none is an answer — it has a keyboard model and restores focus, and any destructive action it offers can be undone.

import { SvImageCropperComponent } from '@styloviz-pro/image-editor';

Demo & usage

Basic usage

Pro

Usage example — open the gallery for the full interactive demo.

Pro

An interactive demo for this component lives in the gallery.

Open live demo

More examples

A square avatar crop

Pro

What the crop will actually produce

Pro

The plan is exposed rather than applied silently: a crop past what a browser will render is downscaled, and past that ceiling a canvas is not an error — it is blank, and toBlob succeeds. The warnings are the only thing standing between the user and a transparent file.

A photograph that is not stored the way it is shown

Pro

A phone photograph is stored sideways with a tag saying which way is up. The component cannot read that tag — it lives in the file's bytes and an <img> does not expose it — so a host that decoded the file passes it in. Leave it at 1 for an image the browser has already auto-oriented.

The geometry on its own

Pro

Exported so a host with its own surface — an inline crop inside an uploader, a canvas editor — gets the same arithmetic rather than a second copy that drifts.

When to use

  • Letting a user choose the part of an image you will store — an avatar, a cover, a thumbnail.
  • You need the crop in the image's own pixels, not the ones on screen.
  • For a before/after wipe rather than a selection, use Image Compare.

Async states

None — this component has nothing to load, so it has no loading, empty or error state to drive.

Inputs

NameTypeDefaultDescription
srcstring''Image URL. Anything an `<img>` accepts, including a blob: or data: URL.
altstring''Alt text for the image being cropped.
crossOrigin'anonymous' | 'use-credentials' | nullnullCORS mode for the image request — `'anonymous'` for a CDN that sends `Access-Control-Allow-Origin`, `'use-credentials'` when it needs cookies. A cross-origin image loaded without it taints the canvas. It displays fine and crops fine on screen; only the export fails, as a `cropFailed` with a security error and no hint why. Leave `null` for same-origin, blob: and data: sources.
aspectnumber (two-way)0width ÷ height. 0 leaves the crop free. Two-way: the aspect switch (`aspectPresets`) writes it, and a new value starts a new crop.
aspectPresetsreadonly SvAspectPreset[][]The aspect switch shown in the toolbar — `SV_ASPECT_PRESETS` is a ready set. Empty shows none.
minSizenumber24Smallest crop, in displayed pixels.
minOutputnumber0Smallest crop in SOURCE pixels — what the exported file must have at least, however far the user zooms in. 0 sets no floor.
orientationSvExifOrientation1The image's EXIF orientation, when the host knows it. The component cannot read this itself, and pretending otherwise would be the lie. The tag lives in the file's bytes; an `<img>` element does not expose it. A host that decoded the file already has it, and one that did not should leave this at 1 — which is correct for every image a browser has already auto-oriented, and that is most of them today.
outputTypeSvImageType'image/png'Format of the exported image: `'image/png'`, `'image/jpeg'` or `'image/webp'`.
strictFormatbooleanfalseRefuse an export in a format other than `outputType`. A browser that cannot encode a type does not say so. `toBlob` falls back to PNG — Safari before 16.4 did this for every WebP export — so a host that asked for a 90 KB WebP gets a 1.2 MB PNG under a `.webp` name. The fallback is always detected (`formatFallback` fires and a dev warning names it); with `strictFormat` it is also refused: `cropFailed` instead of `cropped`, so the host can retry as JPEG.
qualitynumber | undefinedundefinedEncoder quality from 0 to 1 for JPEG and WebP exports; PNG ignores it. Unset uses 0.92 — and only a quality the host actually SET earns the "PNG ignores the quality setting" warning.
flattenTostring'#ffffff'The colour transparency is flattened onto for a format with no alpha. Only JPEG needs it, and only JPEG gets it. A canvas starts transparent and JPEG has no alpha channel, so without a fill a logo on a transparent ground exports as artwork on BLACK — a valid file, no error, and the classic silent corruption. White is the default because it is what printing does and what a user expects.
maxDimensionnumber | undefinedundefinedLongest side the export may have, in px; a larger crop is scaled down. Unset uses the browser canvas limit (16,384).
maxPixelsnumber | undefinedundefinedTotal pixel budget for the export; a larger crop is scaled down to fit. Unset uses the browser canvas limit (16,777,216).
outputSizeSvSize | undefinedundefinedExport at exactly this size, whatever the crop's resolution — an avatar at 256 × 256, a cover at 1500 × 500. Pair it with a matching `aspect`; a mismatch stretches and the plan says so.
disabledbooleanfalseLocks the crop box and its resize handles against pointer and keyboard edits.
shapeSvCropShape'rect'`'round'` crops the ellipse inside the box — a circle at 1:1 — and exports it with transparent corners (PNG or WebP; JPEG flattens them onto `flattenTo`).
showGridbooleantrueRule-of-thirds guides inside the box.
zoomablebooleanfalseTurn on zoom: the mouse wheel, a two-finger pinch and the toolbar's ± buttons, bounded by `minZoom` / `maxZoom`. Off by default so a page that scrolls past a cropper keeps scrolling.
zoomnumber (two-way)1The zoom, as a factor of the fitted picture (1 shows all of it). Two-way; applies only when `zoomable`.
minZoomnumber1The furthest out `zoom` may go; never below 1, the fitted picture.
maxZoomnumber4The furthest in `zoom` may go.
rotationnumber (two-way)0Clockwise quarter turns applied to the picture: 0, 90, 180 or 270. Two-way.
flipXboolean (two-way)falseMirror the picture left to right, as the user sees it. Two-way.
flipYboolean (two-way)falseMirror the picture top to bottom, as the user sees it. Two-way.
straightennumber (two-way)0A free-angle straighten, −45° to 45° clockwise, on top of the quarter turns. The picture grows just enough to keep filling the frame, so no crop reaches an empty corner. Two-way.
filtersSvImageFilters (two-way)SV_NEUTRAL_FILTERSBrightness, contrast and saturation in percent (100 = unchanged), shown live and baked into the export. Two-way.
straightenControlbooleantrueWith `toolbar`, show the straighten slider.
adjustControlsbooleanfalseWith `toolbar`, show the brightness / contrast / saturation sliders.
dragModeSvCropDragMode'crop'What a drag inside the box does. `'crop'` moves the box (and dragging the dimmed area pans a zoomed picture); `'move'` keeps the box still and moves the picture under it, the way a phone's avatar picker does.
toolbarbooleanfalseShow the toolbar: zoom, turn, flip, the aspect switch, reset, undo and redo.
labelsPartial<SvImageCropperLabels>{}The cropper's words for this instance, merged over the app's `provideSvLabels({ imageEditorPro })` and `SV_IMAGE_CROPPER_LABELS`.
initialCropSvCropRect | undefinedundefinedWhere the crop starts, in SOURCE pixels, the first time the image loads — the crop a user saved last time. Unset centres the largest crop of `aspect`.

Outputs

EventPayload typeDescription
cropChangeSvCropRectThe crop, in SOURCE pixels, whenever it changes.
croppedBlobThe rendered image, once `crop()` resolves.
cropFailed{ reason: string; error?: unknown }An export that could not be produced, with the reason.
formatFallback{ requested: SvImageType; produced: string }The browser encoded the export in a different format than `outputType` asked for (a codec it does not have). Fires before `cropped` — or before `cropFailed` under `strictFormat`.
aspectChangenumberEmits the new `aspect` whenever it changes — the output half of `[(aspect)]`.
zoomChangenumberEmits the new `zoom` whenever it changes — the output half of `[(zoom)]`.
rotationChangenumberEmits the new `rotation` whenever it changes — the output half of `[(rotation)]`.
flipXChangebooleanEmits the new `flipX` whenever it changes — the output half of `[(flipX)]`.
flipYChangebooleanEmits the new `flipY` whenever it changes — the output half of `[(flipY)]`.
straightenChangenumberEmits the new `straighten` whenever it changes — the output half of `[(straighten)]`.
filtersChangeSvImageFiltersEmits the new `filters` whenever it changes — the output half of `[(filters)]`.

Customization & theming

  • With no `src` the cropper shows a dashed frame saying there is nothing to crop yet (`data-sv-crop-state="empty"`), and an image that fails to load is replaced by a message (`data-sv-crop-state="error"`) rather than a broken-image icon. No `<img>` is rendered without a source, so an unset image raises no `(cropFailed)`.
  • Lock the shape with `aspect`, bound it with `minSize`, and pick the encoding with `outputType` and `quality`; `maxDimension` and `maxPixels` override the conservative canvas ceilings.
  • `shape="round"` for an avatar mask, `showGrid` for the rule-of-thirds guides, `aspectPresets` for an aspect switch, `minOutput` for the smallest crop the exported file may have, and `outputSize` to export at exactly 256 × 256 whatever the crop's resolution.
  • Editing, all two-way: `zoomable` turns on `[(zoom)]` (wheel, pinch, ±) within `minZoom` / `maxZoom`; `[(rotation)]` in quarter turns, `[(flipX)]` / `[(flipY)]`, a free-angle `[(straighten)]` (−45° to 45°) and `[(filters)]` (brightness, contrast, saturation), all baked into the export. `dragMode="move"` keeps the box still and moves the picture under it.
  • `toolbar` shows zoom, turn, flip, the aspect switch, reset, undo and redo (`straightenControl`, `adjustControls` add the sliders; `labels` words it); `<sv-crop-preview [cropper]="cropper">` shows a live preview of the export.
  • `flattenTo` (default `'#ffffff'`) is the colour a JPEG export is filled with before the draw — JPEG has no alpha, so a transparent ground would otherwise come out black. PNG and WebP keep their transparency and are never filled.
  • Read the selection with `cropChange` (source pixels) or `sourceCrop()`, the rendering with `plan()` and `outputLabel()`, and produce the image with `cropImage()`.
  • `svDefaultCrop`, `svResizeCrop`, `svMoveCrop`, `svClampCrop`, `svCropToSource`, `svOrientedSize`, `svOrientationTransform` and `svOutputPlan` are exported for a host building its own surface.

Best practices

  • Do: Listen to `(formatFallback)` when you export WebP. A browser without the encoder silently hands back a PNG from `toBlob` (Safari before 16.4 did this for every WebP export); the cropper compares the blob's type with `outputType`, warns in dev mode and reports `{ requested, produced }`. Set `[strictFormat]="true"` to get `cropFailed` instead of an oversized PNG under a `.webp` name, then retry as `image/jpeg`.
  • Do: Show `plan().warnings`. A crop the browser cannot render is downscaled, and past that ceiling the canvas is blank rather than an error — `toBlob` still calls back with a valid, fully transparent file.
  • Do: Pass `orientation` when you decoded the file yourself and know the EXIF tag. A portrait phone photo is stored landscape, and cropping the stored orientation lands on a region that is not in the picture.
  • Do: Use JPEG or WebP when you want compression. `toBlob(cb, 'image/png', 0.6)` ignores the 0.6 silently, so a quality slider wired to a PNG export does nothing at all.
  • Don't: Don't send `cropChange` straight to a canvas without checking it is the SOURCE rect. The crop is dragged in display pixels; the emitted rect is already converted, and the two differ by whatever the browser laid the image out at.

Accessibility

  • The crop box is a focusable `role="group"` whose label reports what the crop will produce, and the eight handles are labelled buttons sharing one roving tab stop (Page Up / Page Down and Home / End move between them, each described by a hint) — "drag a box" has no non-pointer equivalent unless one is built, so arrows nudge by a pixel, Shift by ten, `+` / `-` on the box zoom when `zoomable`, and Escape resets.
  • Only the keys it handles are swallowed: Tab and everything else pass through, so the crop box cannot become a focus trap.
  • The dimming mask is `pointer-events-none` and `aria-hidden`, so it neither swallows a drag aimed at a handle nor appears in the accessibility tree.
  • What the crop will produce — including any downscale and its reason — is a `role="status"` caption rather than something the user has to infer from the file they get later.

Feedback on Image Cropper

Spotted a gap in this page, or something that didn't work as described? Comments are GitHub Discussions in the public styloviz/community repo, so posting needs a GitHub account.

Loads giscus.app and GitHub — nothing is fetched until you click.