ImageCropper 圖片裁切
@nscode/handy-ui 提供行內裁切區 HuiImageCropper、確認對話框 HuiImageCropperDialog 與函式入口 openImageCropper()。底層使用 Cropper.js 2,支援矩形、圓形、縮放、旋轉、翻轉、即時預覽,以及 Canvas/Blob/File/Data URL 匯出。檔案皆在瀏覽器內處理,元件不會上傳或永久儲存圖片。
引入
使用 @nscode/handy-ui/cropper 時請先安裝 cropperjs。
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'
沿用應用程式現有的 Vue、@nscode/handy-ui 主題與語言設定。引擎在元件掛載後才動態載入,SSR 不會建立圖片、Canvas 或裁切引擎。
範例
選擇本機檔案與事件
先選擇一張本機圖片,再掛載元件。傳入 File 時,內部來源網址由元件管理,應用程式不必額外建立 Object URL。ready 表示目前的圖片與選取範圍已準備完成;change 回傳畫布中的 CSS 像素座標,而非原圖座標。
<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('請選擇本機圖片;不會上傳至伺服器')
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>本機圖片 <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 }} 次;選取範圍變更 {{ changes }} 次</p>
<pre>{{ rect }}</pre>
</HuiSpace>
</template>
File、Blob 與 URL
三種來源皆可使用。本例的 URL 由使用者選取的原始檔案產生,建立網址的程式須負責釋放;元件不會自行撤銷傳入的 URL。更換來源後,舊的載入、預覽及非同步匯出作業會失效,舊結果不能寫入新圖片。
<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>原始檔案 <input type="file" accept="image/*" @change="choose" /></label>
<label
>src 類型
<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="">空字串</option>
</select></label
>
<HuiImageCropper v-if="source" :src="source" :cross-origin="crossOrigin" :height="260" />
<p>目前類型:{{ mode }};網址僅來自本機原始檔案,不會請求外部圖片。</p>
</HuiSpace>
</template>
本機網址可用來觀察這三種屬性值,但不能據此判定遠端伺服器是否授予 CORS 權限。切換跨來源屬性會重新載入目前的來源。
矩形、圓形、比例與初始覆蓋範圍
rect 採自由比例或指定的 aspectRatio,round 則固定為 1:1。圓形選取範圍具有實際的圓角邊界;匯出時套用圓形遮罩,四角依 output.fill 填色。變更比例會重新調整選取範圍,不會改寫原圖。
<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>本機圖片 <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">自由</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 與 rotate 分別依屬性是否存在來判定受控,未傳入時各自保存狀態。明確傳入 undefined 仍屬受控,實際值會回到預設縮放 1 或角度 0。僅監聽 update:zoom 不會啟用受控模式。父層拒絕或正規化候選值後,引擎會同步至實際值,不會持續反覆發出更新。
<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('尚未操作')
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候選值=${value}`
if (accept.value) zoom.value = value
}
const updateRotate = (value: number) => {
status.value = `rotate候選值=${value}`
if (accept.value) rotate.value = value
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>本機圖片 <input type="file" accept="image/*" @change="choose" /></label>
<label>父層接受候選值 <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 }};實際 zoom={{ zoom }};實際 rotate={{ rotate }}</p>
</HuiSpace>
</template>
工具列、背景與插槽
toolbar=true 顯示七種工具及縮放滑桿;傳入陣列可依序指定工具,false 則隱藏整個工具列。預設工具按鈕只有一個 Tab 停留點,可用左右方向鍵及 Home/End 導覽。替換工具列的插槽提供四個實際方法;自訂按鈕也須遵守停用狀態。
<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>本機圖片 <input type="file" accept="image/*" @change="choose" /></label>
<HuiSpace wrap>
<label
>toolbar
<select v-model="mode">
<option value="all">true</option>
<option value="subset">陣列</option>
<option value="none">false</option>
<option value="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++
}
"
>放大</HuiButton
>
<HuiButton @click="rotateBy(-90)">向左旋轉</HuiButton>
<HuiButton @click="flip('vertical')">垂直翻轉</HuiButton>
<HuiButton @click="reset">重設變換</HuiButton>
</template>
<template #preview><span>自訂預覽區域;此處不會隱含執行匯出。</span></template>
</HuiImageCropper>
<p role="status">自訂放大次數:{{ actions }}</p>
</HuiSpace>
</template>
停用與表單唯讀
元件沒有獨立的 readonly 屬性。置於唯讀的 HuiForm 中時,會沿用既有規則轉為停用;停用會阻擋拖曳、鍵盤及公開的變換方法。getCanvas、getBlob 等查詢匯出方法仍可使用,應用程式可另外限制自己的儲存按鈕。
<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>本機圖片 <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>
八個實例方法與三種輸出格式
可輸出 PNG、JPEG、WebP。只提供寬度或高度時會保持選取範圍的比例;同時提供兩者時,會以指定尺寸為邊界等比例縮放,不會拉伸。兩者都未提供時,會依目前圖片矩陣的倍率,將選取範圍的 CSS 尺寸換算為原圖像素。JPEG 預設填白,PNG/WebP 預設透明。品質參數會傳給瀏覽器編碼器;若瀏覽器不支援所選格式,請檢查實際 Blob 的類型。
<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('尚未匯出')
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長度:${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}位元組`
: `Blob ${result.type},${result.size}位元組`
}
} catch (error) {
if (alive && request === revision)
status.value = error instanceof Error ? error.message : '匯出失敗'
} 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>本機圖片 <input type="file" accept="image/*" @change="choose" /></label>
<HuiSpace wrap>
<label
>格式
<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
>四角填色
<select v-model="fill">
<option value="auto">預設</option>
<option value="white">白色</option>
<option value="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)">放大0.1</HuiButton>
<HuiButton :disabled="!ready" @click="cropper?.rotateBy(90)">旋轉90°</HuiButton>
<HuiButton :disabled="!ready" @click="cropper?.flip('horizontal')">水平翻轉</HuiButton>
<HuiButton :disabled="!ready" @click="cropper?.reset()">重設變換</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="目前的本機裁切結果"
style="max-width: 240px; max-height: 240px; object-fit: contain"
/>
</HuiSpace>
</template>
圖片尚未準備完成時,查詢方法會 reject。換圖、卸載,或在匯出期間變更裁切狀態,都可能使舊匯出 reject;呼叫端也應像本例一樣,核對目前的來源與設定,避免採用過期結果。
宣告式確認對話框
visible 依屬性是否存在來判定受控,預設關閉;明確傳入 undefined 也屬受控關閉。未提供 src 時不建立引擎。按下確定後,只有仍有效的匯出工作階段才能發出 confirm(File);取消、關閉按鈕、遮罩及 Esc 都會發出 cancel。匯出期間會防止重複確認,但仍可取消。若父層拒絕關閉請求,對話框會維持實際顯示狀態。
<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('尚未確認裁切')
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 = '原圖已變更,請重新確認'
return
}
if (preview.value) URL.revokeObjectURL(preview.value)
preview.value = URL.createObjectURL(cropped)
result.value = `確認:${cropped.name},${cropped.size}位元組;原始檔案仍保留`
}
const cancel = () => {
result.value = '已取消或關閉,保留原始檔案與上一份預覽'
}
const error = (cause: Error) => {
result.value = cause.message
}
onBeforeUnmount(() => {
revision++
if (preview.value) URL.revokeObjectURL(preview.value)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>本機圖片 <input type="file" accept="image/*" @change="choose" /></label>
<HuiButton :disabled="!file" @click="open">開啟裁切對話框</HuiButton>
<HuiImageCropperDialog
v-model:visible="visible"
:src="file"
title="確認頭像裁切"
: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="已確認的頭像裁切" width="128" height="128" />
</HuiSpace>
</template>
單獨使用對話框時,載入或匯出失敗會發出 error,不會假裝已確認;匯出失敗會保留視窗供使用者重試。變更 src、關閉後重新開啟或卸載,都會使舊查詢失效,舊作業不會關閉新開啟的對話框。
以函式開啟
openImageCropper(file, options) 在確認後 resolve 實際 File,取消或關閉時 resolve null;圖片載入或匯出失敗則 reject Error,並清理這次建立的容器。SSR 沒有 DOM 時直接回傳 null。可明確傳入目前的 appContext,重用應用程式的依賴與語言,不另建 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('尚未開啟')
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 = '已取消,保留原圖與上一份結果'
return
}
if (preview.value) URL.revokeObjectURL(preview.value)
preview.value = URL.createObjectURL(result)
status.value = `確認:${result.name},${result.type},${result.size}位元組`
} catch (error) {
if (alive && revision === request)
status.value = error instanceof Error ? error.message : '裁切失敗'
} finally {
if (alive) pending.value = false
}
}
onBeforeUnmount(() => {
alive = false
revision++
if (preview.value) URL.revokeObjectURL(preview.value)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<label>本機圖片 <input type="file" accept="image/*" @change="choose" /></label>
<HuiButton :disabled="!file || pending" @click="crop">以函式裁切</HuiButton>
<p role="status">{{ status }}</p>
<img v-if="preview" :src="preview" alt="函式裁切的確認結果" style="max-width: 240px" />
</HuiSpace>
</template>
函式服務會建立獨立的對話框根節點,呼叫端卸載時不會自動代替使用者取消;這次服務會在確認、取消或錯誤後清理。若要讓視窗嚴格跟隨頁面的生命週期,請採用前一個宣告式對話框範例,讓 Vue 在頁面卸載時一併卸載它。
主題與三語介面
主色、遮罩及工具列皆沿用既有主題變數。本文不建立另一個主題 Provider;下例僅在局部覆寫公開的邊框變數。實際應用中,<html> 的主題變更由 useThemeObserver 重新讀取。若只變更局部容器的系統主色,須透過應用程式的更新流程重新整理或掛載裁切區,不能假設根主題觀察器會監看所有局部容器。
<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>本機圖片 <input type="file" accept="image/*" @change="choose" /></label>
<label
>介面語言
<select v-model="language">
<option value="zh-cn">簡體中文</option>
<option value="zh-tw">繁體中文</option>
<option value="en">English</option>
</select></label
>
<label
>局部邊框
<select v-model="color">
<option value="var(--hui-color-primary)">目前主題的主色</option>
<option value="var(--hui-color-success)">成功色</option>
<option value="var(--hui-color-warning)">警告色</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>
上例的局部設定只變更公開邊框變數,不會修改系統主色或引擎選取範圍的顏色。全站主色與深色模式仍由應用程式原有的主題入口切換,引擎主色和遮罩會隨之重新讀取。簡體、繁體及英文資源已內建;其他語言目前回退至簡體,並不表示已提供各語言的獨立譯文。
Props
ImageCropper
| 屬性 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| src | string | File | Blob | 必填 | 網址或實際圖片檔案;空字串不建立引擎 |
| aspectRatio | number | 自由 | 正有限寬高比;round時固定為1 |
| shape | 'rect' | 'round' | 'rect' | 選取範圍形狀 |
| initialCoverage | number | 0.8 | 初始覆蓋比例,合法範圍大於0且不超過1 |
| zoom / v-model:zoom | number | undefined | 1 | 相對初始適應尺寸的絕對倍率;依屬性存在性判定受控 |
| minZoom | number | 0.1 | 最小倍率,須為正有限數 |
| maxZoom | number | 3 | 最大倍率,不小於最小倍率 |
| zoomStep | number | 0.1 | 工具按鈕與滾輪的縮放步長 |
| rotate / v-model:rotate | number | undefined | 0 | 旋轉角度,單位為度;依屬性存在性判定受控 |
| toolbar | boolean | ImageCropperTool[] | true | 全部、指定工具或隱藏;自訂插槽可替換預設內容 |
| background | boolean | true | 顯示格線背景 |
| previews | Array<{ width: number; height?: number }> | — | 即時預覽尺寸;僅使用有效的正尺寸 |
| height | number | string | 360 | 裁切區高度;數字以px計 |
| disabled | boolean | false | 禁止互動與公開變換,仍可查詢匯出;繼承Form停用及唯讀降級狀態 |
| crossOrigin | '' | 'anonymous' | 'use-credentials' | 'anonymous' | URL圖片的跨來源載入方式;變更後建立新的載入工作階段 |
| output | ImageCropperOutput | 見輸出參數 | 預設匯出設定;方法參數可逐欄位覆寫 |
ImageCropperDialog
繼承上述裁切屬性,src 改為選填,並增加下列屬性。zoom、rotate 是否傳入會原樣保留,更新事件的監聽也會轉交實際裁切元件。
| 屬性 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| visible / v-model:visible | boolean | undefined | false | 依屬性存在性判定受控,預設關閉 |
| src | string | File | Blob | undefined | — | 未提供時不掛載裁切引擎 |
| title | string | 目前語言的「裁切圖片」 | 空字串是明確的標題覆寫值 |
| width | number | string | 560 | 對話框寬度;數字以px計 |
輸出參數
| 屬性 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| width | number | 依原圖倍率換算 | 正有限數;只傳一邊時依比例補齊另一邊 |
| height | number | 依原圖倍率換算 | 兩邊都傳入時以contain保持比例,不保證拉伸至指定邊界 |
| type | 'image/png' | 'image/jpeg' | 'image/webp' | 'image/png' | Blob/File/Data URL編碼格式;Canvas本身沒有檔案格式 |
| quality | number | 0.92 | 0~1,傳給瀏覽器的JPEG/WebP編碼器 |
| fill | string | JPEG白色,其餘透明 | 圖片外區域與圓形四角的填色 |
Events
| ImageCropper事件 | 參數 | 說明 |
|---|---|---|
| ready | () | 目前原圖與初始選取範圍已準備完成 |
| error | (error: Error) | 目前圖片載入或初始化失敗;舊工作階段的錯誤不會覆蓋新來源 |
| change | (rect: ImageCropperRect) | 最終實際選取範圍的座標快照;指標拖曳期間合併至結束時通知 |
| update:zoom | (zoom: number) | 縮放候選值;受控時須由父層回填才成為實際值 |
| update:rotate | (rotate: number) | 旋轉候選值;受控時須由父層回填才成為實際值 |
| ImageCropperDialog事件 | 參數 | 說明 |
|---|---|---|
| update:visible | (visible: boolean) | 請求變更顯示狀態,父層可接受或拒絕 |
| confirm | (file: File) | 目前工作階段匯出成功後請求關閉;回呼切換的新工作階段不會被舊作業關閉 |
| cancel | () | 取消按鈕、關閉按鈕、遮罩或Esc請求關閉,未匯出確認檔案 |
| error | (error: Error) | 載入或匯出失敗,不會發出假的confirm |
匯出方法本身失敗時會 reject;行內裁切元件的 error 並非所有匯出 Promise 的統一錯誤處理器。對話框會在確認流程中捕捉匯出錯誤,再發出 error。
Slots
| 插槽 | 參數 | 說明 |
|---|---|---|
| toolbar | { zoomBy, rotateBy, flip, reset } | 替換工具列;toolbar=false時不渲染 |
| preview | 無 | 替換預覽區域,不會內建執行匯出 |
這兩個插槽也可傳給 HuiImageCropperDialog,再由它轉交實際裁切元件。
方法
HuiImageCropper 的模板ref類型為 ImageCropperExpose。對話框不另外提供第二套裁切實例方法,結果透過 confirm 交回。
| 方法 | 參數與回傳值 | 說明 |
|---|---|---|
| getCanvas | (output?: ImageCropperOutput) => Promise<HTMLCanvasElement> | 目前選取範圍的實際Canvas;圓形已套用遮罩 |
| getBlob | (output?: ImageCropperOutput) => Promise<Blob> | 編碼失敗或跨來源污染時reject |
| getFile | (name?: string, output?: ImageCropperOutput) => Promise<File> | 預設以原始檔名替換對應副檔名;URL/一般Blob預設為cropped-image |
| getDataURL | (output?: ImageCropperOutput) => Promise<string> | 匯出對應格式的Data URL |
| zoomBy | (delta: number) => void | 將目前倍率加減delta,範圍受min/maxZoom限制 |
| rotateBy | (degree: number) => void | 相對旋轉指定角度 |
| flip | (direction: 'horizontal' | 'vertical') => void | 水平或垂直翻轉 |
| reset | () => void | 還原初始適應變換、旋轉與選取範圍;仍遵守zoom/rotate的受控回填 |
openImageCropper
function openImageCropper(
file: File | string,
options?: OpenImageCropperOptions
): Promise<File | null>
OpenImageCropperOptions 包含 visible、src 以外的對話框屬性,以及選填的 appContext: AppContext。不會另建全域快取、第二個主題Provider或新的語言單例。
類型
公開類型皆由 @nscode/handy-ui/cropper 引入:ImageCropperProps、ImageCropperEmits、ImageCropperExpose、ImageCropperSlots、ImageCropperShape、ImageCropperTool、ImageCropperRect、ImageCropperOutput、ImageCropperDialogProps、ImageCropperDialogEmits、OpenImageCropperOptions。三語資源為 cropperLocaleZhCn、cropperLocaleZhTw、cropperLocaleEn。
type ImageCropperShape = 'rect' | 'round'
type ImageCropperTool =
| 'zoomIn'
| 'zoomOut'
| 'rotateLeft'
| 'rotateRight'
| 'flipHorizontal'
| 'flipVertical'
| 'reset'
interface ImageCropperRect {
x: number
y: number
width: number
height: number
}