ImageCropper
@nscode/handy-ui provides the inline HuiImageCropper, the confirmation dialog HuiImageCropperDialog, and the openImageCropper() service. It uses Cropper.js 2 and supports rectangular and round selections, zooming, rotation, flipping, live previews, and Canvas/Blob/File/Data URL export. Files are processed in the browser; the components do not upload or persist images.
Import
Install cropperjs to use @nscode/handy-ui/cropper.
pnpm add cropperjs@^2.3.1
import '@nscode/handy-ui/style.css'
import { HuiImageCropper, HuiImageCropperDialog, openImageCropper } from '@nscode/handy-ui/cropper'
import type { ImageCropperExpose, ImageCropperOutput } from '@nscode/handy-ui/cropper'
Reuse the application’s Vue instance, @nscode/handy-ui theme, and language configuration. The engine loads dynamically after mounting. SSR does not create images, canvases, or a cropper engine.
Examples
Selecting a local file and observing events
Select a local image before mounting the component. Passing a File lets the component manage its internal source URL, so the application does not need to create an Object URL for this input. ready means the current image and selection are ready. change reports CSS pixel coordinates within the canvas, rather than coordinates in the original image.
<script setup lang="ts">
import { ref, shallowRef } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiImageCropper } from '@nscode/handy-ui/cropper'
import type { ImageCropperRect } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const ready = ref(0)
const changes = ref(0)
const rect = ref<ImageCropperRect>()
const status = ref('Choose a local image; it will not be uploaded')
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
const selected = input.files?.[0]
input.value = ''
if (selected) {
file.value = selected
status.value = selected.name
}
}
const change = (value: ImageCropperRect) => {
rect.value = value
changes.value++
}
const error = (value: Error) => {
status.value = value.message
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<HuiImageCropper
v-if="file"
:src="file"
:height="300"
@ready="ready++"
@change="change"
@error="error"
/>
<p role="status">
{{ status }}; ready events: {{ ready }}; selection changes: {{ changes }} times
</p>
<pre>{{ rect }}</pre>
</HuiSpace>
</template>
File, Blob, and URL sources
All three source types are supported. The example creates a URL from a file selected by the user. The application owns and must revoke URLs it creates; the component never revokes an externally supplied URL. Changing the source invalidates old loading, preview, and asynchronous export work, so an old result cannot overwrite a new image.
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiImageCropper } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const mode = ref<'file' | 'blob' | 'url'>('file')
const crossOrigin = ref<'' | 'anonymous' | 'use-credentials'>('anonymous')
const url = ref('')
const blob = computed(() =>
file.value ? new Blob([file.value], { type: file.value.type }) : undefined
)
const source = computed(() =>
mode.value === 'url' ? url.value : mode.value === 'blob' ? blob.value : file.value
)
watch(
file,
(selected) => {
if (url.value) URL.revokeObjectURL(url.value)
url.value = selected ? URL.createObjectURL(selected) : ''
},
{ flush: 'sync' }
)
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
onBeforeUnmount(() => {
if (url.value) URL.revokeObjectURL(url.value)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Original file <input type="file" accept="image/*" @change="choose" /></label>
<label
>src type
<select v-model="mode">
<option value="file">File</option>
<option value="blob">Blob</option>
<option value="url">URL</option>
</select></label
>
<label
>crossOrigin
<select v-model="crossOrigin">
<option value="anonymous">anonymous</option>
<option value="use-credentials">use-credentials</option>
<option value="">Empty string</option>
</select></label
>
<HuiImageCropper v-if="source" :src="source" :cross-origin="crossOrigin" :height="260" />
<p>
Current type: {{ mode }}; URLs come only from the local original file. No external images are
requested.
</p>
</HuiSpace>
</template>
The local URL in this example demonstrates the three property values. It does not establish permission under a remote server’s CORS policy. Changing the cross-origin setting reloads the current source.
Rectangular and round selections, aspect ratio, and initial coverage
rect uses a free aspect ratio or the supplied aspectRatio; round always uses 1:1. A round selection follows its rounded boundary. Export applies a circular mask, with the corners filled according to output.fill. Changing the ratio adjusts the selection without modifying the original image.
<script setup lang="ts">
import { computed, ref, shallowRef } from 'vue'
import { HuiSpace } from '@nscode/handy-ui'
import { HuiImageCropper } from '@nscode/handy-ui/cropper'
import type { ImageCropperShape } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const shape = ref<ImageCropperShape>('rect')
const ratio = ref('free')
const coverage = ref(0.8)
const aspectRatio = computed(() => (ratio.value === 'free' ? undefined : Number(ratio.value)))
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<HuiSpace wrap>
<label
>shape
<select v-model="shape">
<option value="rect">rect</option>
<option value="round">round</option>
</select></label
>
<label
>aspectRatio
<select v-model="ratio">
<option value="free">Free</option>
<option value="1">1:1</option>
<option :value="String(16 / 9)">16:9</option>
<option :value="String(4 / 3)">4:3</option>
</select></label
>
<label
>initialCoverage
<select v-model="coverage">
<option :value="0.5">0.5</option>
<option :value="0.8">0.8</option>
<option :value="1">1</option>
</select></label
>
</HuiSpace>
<HuiImageCropper
v-if="file"
:src="file"
:shape="shape"
:aspect-ratio="aspectRatio"
:initial-coverage="coverage"
:height="300"
:previews="[{ width: 96, height: 96 }, { width: 48 }]"
/>
</HuiSpace>
</template>
Zoom, rotation, and rejected controlled updates
zoom and rotate are independently controlled by prop presence. Each keeps internal state when omitted. An explicit undefined remains controlled and uses the default zoom of 1 or rotation of 0. Listening to update:zoom alone does not make zoom controlled. When the parent rejects or normalizes a candidate, the engine reconciles to the actual value without repeatedly emitting updates.
<script setup lang="ts">
import { ref, shallowRef } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiImageCropper } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const accept = ref(true)
const zoom = ref(1)
const rotate = ref(0)
const status = ref('No action yet')
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
const updateZoom = (value: number) => {
status.value = `zoom candidate=${value}`
if (accept.value) zoom.value = value
}
const updateRotate = (value: number) => {
status.value = `rotate candidate=${value}`
if (accept.value) rotate.value = value
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<label>Parent accepts candidates <HuiSwitch v-model="accept" /></label>
<HuiImageCropper
v-if="file"
:src="file"
:zoom="zoom"
:rotate="rotate"
:min-zoom="0.5"
:max-zoom="2"
:zoom-step="0.2"
:height="280"
@update:zoom="updateZoom"
@update:rotate="updateRotate"
/>
<p role="status">{{ status }}; actual zoom={{ zoom }}; actual rotate={{ rotate }}</p>
</HuiSpace>
</template>
Toolbar, background, and slots
toolbar=true displays seven tools and a zoom slider. An array selects tools in order; false hides the entire toolbar. The default toolbar has one button in the Tab order, with Left/Right and Home/End navigation. The replacement toolbar slot receives four actual methods. Custom buttons must also respect the disabled state.
<script setup lang="ts">
import { ref, shallowRef } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiImageCropper } from '@nscode/handy-ui/cropper'
import type { ImageCropperTool } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const background = ref(true)
const mode = ref<'all' | 'subset' | 'none' | 'slot'>('all')
const subset: ImageCropperTool[] = ['zoomIn', 'zoomOut', 'rotateRight', 'reset']
const actions = ref(0)
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<HuiSpace wrap>
<label
>toolbar
<select v-model="mode">
<option value="all">true</option>
<option value="subset">Array</option>
<option value="none">false</option>
<option value="slot">Custom slot</option>
</select></label
>
<label>background <HuiSwitch v-model="background" /></label>
</HuiSpace>
<HuiImageCropper
v-if="file"
:src="file"
:toolbar="mode === 'none' ? false : mode === 'subset' ? subset : true"
:background="background"
:height="280"
>
<template v-if="mode === 'slot'" #toolbar="{ zoomBy, rotateBy, flip, reset }">
<HuiButton
@click="
() => {
zoomBy(0.1)
actions++
}
"
>Zoom in</HuiButton
>
<HuiButton @click="rotateBy(-90)">Rotate left</HuiButton>
<HuiButton @click="flip('vertical')">Flip vertically</HuiButton>
<HuiButton @click="reset">Reset transformations</HuiButton>
</template>
<template #preview
><span>Custom preview region; no implicit export occurs here.</span></template
>
</HuiImageCropper>
<p role="status">Custom zoom actions: {{ actions }}</p>
</HuiSpace>
</template>
Disabled and readonly forms
The component has no separate readonly prop. Inside a readonly HuiForm, it follows the existing form rule and becomes disabled. This blocks dragging, keyboard interaction, and public transform methods. Export queries such as getCanvas and getBlob remain available; the application can restrict its own save button separately.
<script setup lang="ts">
import { ref, shallowRef } from 'vue'
import { HuiForm, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import { HuiImageCropper } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const disabled = ref(false)
const readonly = ref(false)
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<HuiSpace wrap
><label>disabled <HuiSwitch v-model="disabled" /></label
><label>Form readonly <HuiSwitch v-model="readonly" /></label
></HuiSpace>
<HuiForm :readonly="readonly"
><HuiImageCropper v-if="file" :src="file" :disabled="disabled" :height="260"
/></HuiForm>
</HuiSpace>
</template>
Eight instance methods and three output formats
Output supports PNG, JPEG, and WebP. Supplying only width or height preserves the selection ratio. Supplying both contains the result within those dimensions while preserving its ratio, without stretching. With neither supplied, the current image-matrix scale converts CSS selection dimensions into original-image pixels. JPEG defaults to a white fill; PNG/WebP default to transparency. Quality is passed to the browser encoder. Check the actual Blob type when the browser does not support the requested format.
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { HuiButton, HuiSpace } from '@nscode/handy-ui'
import { HuiImageCropper } from '@nscode/handy-ui/cropper'
import type { ImageCropperExpose, ImageCropperOutput } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const cropper = ref<ImageCropperExpose>()
const ready = ref(false)
const pending = ref(false)
const type = ref<NonNullable<ImageCropperOutput['type']>>('image/png')
const fill = ref('auto')
const output = computed<ImageCropperOutput>(() => ({
width: 192,
type: type.value,
quality: 0.8,
...(fill.value === 'auto' ? {} : { fill: fill.value })
}))
const preview = ref('')
const status = ref('Not exported yet')
let alive = true
let revision = 0
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
watch(
[file, type, fill],
() => {
revision++
pending.value = false
},
{ flush: 'sync' }
)
watch(
file,
() => {
ready.value = false
},
{ flush: 'sync' }
)
const selectionChanged = () => {
revision++
}
const exportResult = async (kind: 'canvas' | 'blob' | 'file' | 'dataURL') => {
const api = cropper.value
if (!api || !ready.value || pending.value) return
const request = revision
pending.value = true
try {
if (kind === 'canvas') {
const canvas = await api.getCanvas(output.value)
if (alive && request === revision) status.value = `Canvas ${canvas.width}×${canvas.height}`
} else if (kind === 'dataURL') {
const result = await api.getDataURL(output.value)
if (!alive || request !== revision) return
if (preview.value.startsWith('blob:')) URL.revokeObjectURL(preview.value)
preview.value = result
status.value = `Data URL length: ${result.length}`
} else {
const result =
kind === 'file'
? await api.getFile(undefined, output.value)
: await api.getBlob(output.value)
if (!alive || request !== revision) return
if (preview.value.startsWith('blob:')) URL.revokeObjectURL(preview.value)
preview.value = URL.createObjectURL(result)
status.value =
result instanceof File
? `${result.name},${result.type},${result.size} bytes`
: `Blob ${result.type},${result.size} bytes`
}
} catch (error) {
if (alive && request === revision)
status.value = error instanceof Error ? error.message : 'Export failed'
} finally {
if (alive && request === revision) pending.value = false
}
}
onBeforeUnmount(() => {
alive = false
revision++
if (preview.value.startsWith('blob:')) URL.revokeObjectURL(preview.value)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<HuiSpace wrap>
<label
>Format
<select v-model="type">
<option value="image/png">PNG</option>
<option value="image/jpeg">JPEG</option>
<option value="image/webp">WebP</option>
</select></label
>
<label
>Corner fill
<select v-model="fill">
<option value="auto">Default</option>
<option value="white">White</option>
<option value="transparent">Transparent</option>
</select></label
>
</HuiSpace>
<HuiImageCropper
v-if="file"
ref="cropper"
:src="file"
shape="round"
:height="280"
:output="output"
@ready="ready = true"
@change="selectionChanged"
/>
<HuiSpace wrap>
<HuiButton :disabled="!ready" @click="cropper?.zoomBy(0.1)">Zoom in by 0.1</HuiButton>
<HuiButton :disabled="!ready" @click="cropper?.rotateBy(90)">Rotate 90°</HuiButton>
<HuiButton :disabled="!ready" @click="cropper?.flip('horizontal')"
>Flip horizontally</HuiButton
>
<HuiButton :disabled="!ready" @click="cropper?.reset()">Reset transformations</HuiButton>
<HuiButton :disabled="!ready || pending" @click="exportResult('canvas')">getCanvas</HuiButton>
<HuiButton :disabled="!ready || pending" @click="exportResult('blob')">getBlob</HuiButton>
<HuiButton :disabled="!ready || pending" @click="exportResult('file')">getFile</HuiButton>
<HuiButton :disabled="!ready || pending" @click="exportResult('dataURL')"
>getDataURL</HuiButton
>
</HuiSpace>
<p role="status">{{ status }}</p>
<img
v-if="preview"
:src="preview"
alt="Current local crop result"
style="max-width: 240px; max-height: 240px; object-fit: contain"
/>
</HuiSpace>
</template>
Query methods reject when the image is not ready. Changing the source, unmounting, or changing crop state during export can also reject an old export. Callers should additionally check the current source and configuration, as this example does, instead of treating a late result as current.
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.
Theme and three interface languages
Primary color, overlay, and toolbar use the existing theme variables. This document does not introduce another theme Provider. The example only overrides a public border variable locally. In an application, useThemeObserver rereads theme changes on <html>. If only a local container’s system primary color changes, refresh or remount the cropper through the application’s update flow; the root theme observer does not observe every local container.
<script setup lang="ts">
import { computed, ref, shallowRef } from 'vue'
import { HuiConfigProvider, HuiSpace, localeEn, localeZhCn, localeZhTw } from '@nscode/handy-ui'
import { HuiImageCropper } from '@nscode/handy-ui/cropper'
const file = shallowRef<File>()
const language = ref('zh-cn')
const color = ref('var(--hui-color-primary)')
const locale = computed(() =>
language.value === 'en' ? localeEn : language.value === 'zh-tw' ? localeZhTw : localeZhCn
)
const choose = (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files?.[0]) file.value = input.files[0]
input.value = ''
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>Local image <input type="file" accept="image/*" @change="choose" /></label>
<label
>Interface language
<select v-model="language">
<option value="zh-cn">Simplified Chinese</option>
<option value="zh-tw">Traditional Chinese</option>
<option value="en">English</option>
</select></label
>
<label
>Local border
<select v-model="color">
<option value="var(--hui-color-primary)">Current theme primary color</option>
<option value="var(--hui-color-success)">Success color</option>
<option value="var(--hui-color-warning)">Warning color</option>
</select></label
>
<HuiConfigProvider :locale="locale">
<div :style="{ '--hui-image-cropper-border-color': color }">
<HuiImageCropper v-if="file" :src="file" :height="260" :previews="[{ width: 64 }]" />
</div>
</HuiConfigProvider>
</HuiSpace>
</template>
The local configuration above changes only the public border variable, without changing the system primary color or the engine’s selection color. Use the application’s existing theme controls for global primary color and dark mode; the engine rereads its primary and overlay colors. Three language resources are built in. Other languages currently fall back to Simplified Chinese, which does not mean independent translations have been delivered.
Props
ImageCropper
| Prop | Type | Default | Description |
|---|---|---|---|
| src | string | File | Blob | Required | URL or an actual image file; an empty string does not create an engine |
| 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 |
ImageCropperDialog
Inherits the cropper props above, makes src optional, and adds the following props. The presence of zoom and rotate is preserved when forwarding them, and update listeners are forwarded to the actual cropper.
| 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 |
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
| ImageCropper event | Parameters | Description |
|---|---|---|
| ready | () | The current source image and initial selection are ready |
| error | (error: Error) | Current-image loading or initialization failure; old-session errors cannot overwrite a new source |
| change | (rect: ImageCropperRect) | Snapshot of the final actual selection; pointer-drag notifications are combined until the drag ends |
| update:zoom | (zoom: number) | Zoom candidate; a controlled parent must update its prop for it to become the actual value |
| update:rotate | (rotate: number) | Rotation candidate; a controlled parent must update its prop for it to become the actual value |
| 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 |
Export methods reject their own failures. The inline cropper’s error event is not a universal handler for every export Promise. The dialog catches export errors during confirmation and emits error.
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 |
Both slots can also be passed to HuiImageCropperDialog, which forwards them to the actual cropper.
Methods
Use ImageCropperExpose for an HuiImageCropper template ref. The dialog does not expose a second set of cropper-instance methods; it returns the result through confirm.
| Method | Parameters and return value | Description |
|---|---|---|
| getCanvas | (output?: ImageCropperOutput) => Promise<HTMLCanvasElement> | Actual Canvas for the current selection, including the circular mask when applicable |
| getBlob | (output?: ImageCropperOutput) => Promise<Blob> | Rejects on encoding failure or a cross-origin-tainted canvas |
| getFile | (name?: string, output?: ImageCropperOutput) => Promise<File> | Uses the source file name with the matching extension by default; URL/plain Blob sources default to cropped-image |
| getDataURL | (output?: ImageCropperOutput) => Promise<string> | Export a Data URL in the requested format |
| zoomBy | (delta: number) => void | Add delta to the actual zoom, constrained by min/maxZoom |
| rotateBy | (degree: number) => void | Rotate by a relative angle |
| flip | (direction: 'horizontal' | 'vertical') => void | Flip horizontally or vertically |
| reset | () => void | Restore the initial fit, rotation, and selection, while respecting controlled zoom/rotate updates |
openImageCropper
function openImageCropper(
file: File | string,
options?: OpenImageCropperOptions
): Promise<File | null>
OpenImageCropperOptions contains the dialog props except visible and src, plus an optional appContext: AppContext. It introduces no separate global cache, second theme Provider, or new language singleton.
Types
Import public types from @nscode/handy-ui/cropper: ImageCropperProps, ImageCropperEmits, ImageCropperExpose, ImageCropperSlots, ImageCropperShape, ImageCropperTool, ImageCropperRect, ImageCropperOutput, ImageCropperDialogProps, ImageCropperDialogEmits, and OpenImageCropperOptions. CropperLocale and CropperLocaleSchema describe the extension language resources. The three resources are cropperLocaleZhCn, cropperLocaleZhTw, and cropperLocaleEn.
type ImageCropperShape = 'rect' | 'round'
type ImageCropperTool =
| 'zoomIn'
| 'zoomOut'
| 'rotateLeft'
| 'rotateRight'
| 'flipHorizontal'
| 'flipVertical'
| 'reset'
interface ImageCropperRect {
x: number
y: number
width: number
height: number
}