item-atlas/apps/h5/src/components/PhotoCrop.vue

96 lines
4.3 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { Crop, X } from '@lucide/vue'
import { message } from '../api'
const props = defineProps<{ file: File }>()
const emit = defineEmits<{ close: []; ready: [photo: Blob] }>()
const holder = ref<HTMLElement>()
const dialog = ref<HTMLDialogElement>()
const image = new Image()
const imageURL = URL.createObjectURL(props.file)
const canvas = document.createElement('canvas')
canvas.width = 600
canvas.height = 600
canvas.setAttribute('aria-label', '照片裁剪预览')
const zoom = ref(1)
const center = ref({ x: 0.5, y: 0.5 })
const loading = ref(true)
const busy = ref(false)
const error = ref('')
let drag: { pointer: number; x: number; y: number; center: { x: number; y: number } } | undefined
function source() {
const side = Math.min(image.naturalWidth, image.naturalHeight) / zoom.value
return { side, x: (image.naturalWidth - side) * center.value.x, y: (image.naturalHeight - side) * center.value.y }
}
function paint(target: HTMLCanvasElement) {
const ctx = target.getContext('2d')
if (!ctx || !image.naturalWidth) return
const crop = source()
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, target.width, target.height)
ctx.drawImage(image, crop.x, crop.y, crop.side, crop.side, 0, 0, target.width, target.height)
}
function move(event: PointerEvent) {
if (!drag || event.pointerId !== drag.pointer) return
const crop = source()
const scale = crop.side / Math.max(1, holder.value?.clientWidth ?? 300)
const limit = (position: number) => Math.max(0, Math.min(1, position))
center.value = {
x: limit(drag.center.x - (event.clientX - drag.x) * scale / Math.max(1, image.naturalWidth - crop.side)),
y: limit(drag.center.y - (event.clientY - drag.y) * scale / Math.max(1, image.naturalHeight - crop.side)),
}
}
function start(event: PointerEvent) {
if (loading.value || error.value || event.button !== 0) return
drag = { pointer: event.pointerId, x: event.clientX, y: event.clientY, center: center.value }
holder.value?.setPointerCapture(event.pointerId)
}
async function exportCrop() {
if (loading.value || busy.value || error.value) return
busy.value = true
try {
const target = document.createElement('canvas')
target.width = target.height = Math.min(1440, Math.max(200, Math.round(source().side)))
paint(target)
const blob = await new Promise<Blob | null>((resolve) => target.toBlob(resolve, 'image/jpeg', 0.84))
if (!blob || blob.size > 5 * 1024 * 1024) throw new Error('裁剪后照片仍超过 5 MiB,请缩小后重试。')
emit('ready', blob)
} catch (cause) { error.value = message(cause) }
finally { busy.value = false }
}
watch([zoom, center], () => paint(canvas))
onMounted(() => {
dialog.value?.showModal()
holder.value?.append(canvas)
image.onload = () => {
loading.value = false
if (image.naturalWidth * image.naturalHeight > 54_000_000) error.value = '照片分辨率过高,请选择一张较小的照片。'
else paint(canvas)
}
image.onerror = () => { loading.value = false; error.value = '浏览器无法读取这张照片,请换用 JPEG、PNG 或 WebP。' }
image.src = imageURL
})
onBeforeUnmount(() => { image.onload = image.onerror = null; image.src = ''; URL.revokeObjectURL(imageURL) })
</script>
<template>
<dialog ref="dialog" class="photo-dialog" @cancel.prevent="emit('close')">
<header class="section-top"><h2>裁剪照片</h2><button class="square quiet" aria-label="关闭裁剪" @click="emit('close')"><X :size="20" /></button></header>
<div ref="holder" class="crop-area" @pointerdown="start" @pointermove="move" @pointerup="drag = undefined" @pointercancel="drag = undefined"></div>
<p v-if="error" class="notice error" role="alert">{{ error }}</p>
<p v-else-if="loading" class="secondary" role="status">正在读取照片…</p>
<div v-else class="form">
<label>缩放 <slider :value="Math.round(zoom * 100)" :min="100" :max="300" :step="5" active-color="#1b604a"
@changing="zoom = $event.detail.value / 100" @change="zoom = $event.detail.value / 100" /></label>
<div class="form-actions"><button @click="center = { x: .5, y: .5 }; zoom = 1">重置</button><button class="primary" :disabled="busy" @click="exportCrop"><Crop :size="16" />使用照片</button></div>
</div>
</dialog>
</template>