ImageCropperDialog
HuiImageCropperDialog crops images in a modal, uses visible for visibility, and emits an actual File on confirmation. Processing stays in the browser; the component does not upload or persist files. See ImageCropper for inline cropping and export options.
Import
Install cropperjs to use @nscode/handy-ui/cropper.
pnpm add cropperjs@^2.3.1
import '@nscode/handy-ui/style.css'
import { HuiImageCropperDialog, openImageCropper } from '@nscode/handy-ui/cropper'
import type { ImageCropperDialogProps, OpenImageCropperOptions } from '@nscode/handy-ui/cropper'
Examples
Declarative confirmation dialog
visible is controlled by prop presence and defaults to closed. Explicit undefined remains a controlled closed value. Without src, no engine is created. Confirmation emits confirm(File) only while its export session remains current. Cancel, the close button, the mask, and Esc emit cancel. Export blocks duplicate confirmation while cancellation remains available. If the parent rejects a close request, the actual visible value is preserved.
<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiImageCropperDialog } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const visible = ref(false)
const preview = ref('')
const result = ref('No crop confirmed yet')
let revision = 0
let opened = 0
watch(
file,
() => {
revision++
},
{ flush: 'sync' }
)
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
const open = () => {
if (file.value) {
opened = revision
visible.value = true
}
}
const confirm = (cropped: File) => {
if (opened !== revision) {
result.value = 'Original image changed; confirm again'
return
}
if (preview.value) URL.revokeObjectURL(preview.value)
preview.value = URL.createObjectURL(cropped)
result.value = `Confirmed: ${cropped.name},${cropped.size} bytes; original file preserved`
}
const cancel = () => {
result.value = 'Canceled or closed; original file and previous preview preserved'
}
const error = (cause: Error) => {
result.value = cause.message
}
onBeforeUnmount(() => {
revision++
if (preview.value) URL.revokeObjectURL(preview.value)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<HuiButton :disabled="!file" @click="open">Open crop dialog</HuiButton>
<HuiImageCropperDialog
v-model:visible="visible"
:src="file"
title="Confirm avatar crop"
:width="600"
shape="round"
:output="{ width: 128, type: 'image/png' }"
@confirm="confirm"
@cancel="cancel"
@error="error"
/>
<p role="status">{{ result }}</p>
<img v-if="preview" :src="preview" alt="Confirmed avatar crop" width="128" height="128" />
</HuiSpace>
</template>
When using the dialog directly, loading or export failures emit error without a false confirmation. Export failures keep the dialog open for retry. Changing src, closing and reopening, or unmounting invalidates an old query, which cannot close a newly opened dialog.
Opening with a function
openImageCropper(file, options) resolves with the actual File on confirmation, resolves with null on cancellation or closing, and rejects with an Error on loading or export failure after cleaning up its container. During SSR without a DOM, it returns null. Pass the current appContext explicitly to reuse application dependencies and language without creating another Provider.
<script setup lang="ts">
import { getCurrentInstance, onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { openImageCropper } from '@nscode/handy-ui/cropper'
const appContext = getCurrentInstance()?.appContext
const file = shallowRef<File>()
const pending = ref(false)
const status = ref('Not opened yet')
const preview = ref('')
let alive = true
let revision = 0
watch(
file,
() => {
revision++
},
{ flush: 'sync' }
)
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
const crop = async () => {
const source = file.value
if (!source || pending.value) return
const request = revision
pending.value = true
try {
const result = await openImageCropper(source, {
appContext,
aspectRatio: 4 / 3,
output: { width: 240, type: 'image/jpeg' }
})
if (!alive || revision !== request || source !== file.value) return
if (!result) {
status.value = 'Canceled; original image and previous result preserved'
return
}
if (preview.value) URL.revokeObjectURL(preview.value)
preview.value = URL.createObjectURL(result)
status.value = `Confirmed: ${result.name},${result.type},${result.size} bytes`
} catch (error) {
if (alive && revision === request)
status.value = error instanceof Error ? error.message : 'Crop failed'
} finally {
if (alive) pending.value = false
}
}
onBeforeUnmount(() => {
alive = false
revision++
if (preview.value) URL.revokeObjectURL(preview.value)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<HuiButton :disabled="!file || pending" @click="crop">Crop with the service</HuiButton>
<p role="status">{{ status }}</p>
<img
v-if="preview"
:src="preview"
alt="Confirmed crop service result"
style="max-width: 240px"
/>
</HuiSpace>
</template>
The service owns an independent dialog root. Unmounting the caller does not automatically make a cancellation choice for the user; the service cleans up after confirmation, cancellation, or error. For strict page-lifecycle ownership, use the preceding declarative dialog so Vue unmounts it with the page.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| visible / v-model:visible | boolean | undefined | false | Controlled by prop presence; closed by default |
| src | string | File | Blob | undefined | — | No engine is mounted when omitted |
| title | string | Localized crop-image title | An empty string explicitly overrides the title |
| width | number | string | 560 | Dialog width; numeric values use px |
Inherited crop properties
The following properties match HuiImageCropper, except that src is optional. zoom and rotate are controlled by prop presence; listeners reach the actual crop body, and only parent acceptance changes the actual values.
| Prop | Type | Default | Description |
|---|---|---|---|
| aspectRatio | number | Free | Positive finite width-to-height ratio; fixed to 1 with round |
| shape | 'rect' | 'round' | 'rect' | Selection shape |
| initialCoverage | number | 0.8 | Initial coverage ratio, greater than 0 and at most 1 |
| zoom / v-model:zoom | number | undefined | 1 | Absolute zoom relative to the initial fit; controlled by prop presence |
| minZoom | number | 0.1 | Positive finite minimum zoom |
| maxZoom | number | 3 | Maximum zoom, at least the minimum |
| zoomStep | number | 0.1 | Zoom step for toolbar buttons and the mouse wheel |
| rotate / v-model:rotate | number | undefined | 0 | Rotation in degrees; controlled by prop presence |
| toolbar | boolean | ImageCropperTool[] | true | Display all tools, selected tools, or no toolbar; a slot can replace its content |
| background | boolean | true | Display the grid background |
| previews | Array<{ width: number; height?: number }> | — | Live preview sizes; only valid positive dimensions are used |
| height | number | string | 360 | Crop-area height; numeric values use px |
| disabled | boolean | false | Block interaction and public transforms while preserving export queries; inherits form disabled and readonly fallback |
| crossOrigin | '' | 'anonymous' | 'use-credentials' | 'anonymous' | Cross-origin mode for URL images; changing it starts a new loading session |
| output | ImageCropperOutput | See output options | Default export options; method options override individual fields |
Output options
| Prop | Type | Default | Description |
|---|---|---|---|
| width | number | Derived from original-image scale | Positive finite dimension; with only one dimension supplied, the other follows the selection ratio |
| height | number | Derived from original-image scale | With both dimensions supplied, contain preserves the ratio rather than stretching to exact boundaries |
| type | 'image/png' | 'image/jpeg' | 'image/webp' | 'image/png' | Blob/File/Data URL encoding; a Canvas itself has no file format |
| quality | number | 0.92 | 0–1, passed to the browser’s JPEG/WebP encoder |
| fill | string | White for JPEG, transparent otherwise | Fill outside the image and in the corners of a round selection |
Events
| ImageCropperDialog event | Parameters | Description |
|---|---|---|
| update:visible | (visible: boolean) | Request a visibility change that the parent can accept or reject |
| confirm | (file: File) | Current-session export succeeded; closing is requested afterward, without closing a new session opened in the callback |
| cancel | () | The cancel button, close button, mask, or Esc requested closing; no exported File is confirmed |
| error | (error: Error) | Loading or export failure, without a false confirm |
Slots
| Slot | Parameters | Description |
|---|---|---|
| toolbar | { zoomBy, rotateBy, flip, reset } | Replace the toolbar; not rendered when toolbar=false |
| preview | None | Replace the preview area; does not automatically execute an export |
Methods
The dialog exposes no separate instance methods. It returns the result through confirm(File). Use ImageCropper when direct crop queries or transform methods are required.
function openImageCropper(
file: File | string,
options?: OpenImageCropperOptions
): Promise<File | null>
OpenImageCropperOptions contains dialog properties other than visible and src, plus an optional current AppContext. Cancellation or closing resolves null; loading or export errors reject. Without a DOM, SSR resolves null.
Types
Import ImageCropperDialogProps, ImageCropperDialogEmits, and OpenImageCropperOptions, plus shared ImageCropperOutput, ImageCropperTool, and ImageCropperSlots, from @nscode/handy-ui/cropper.