在 Vue3+Vite 中使用裁剪选择来限制边界会使裁剪选择设置的宽度和高度失效
const fileInputRef = ref<HTMLInputElement | null>(null) const cropperImageDom = new Image() const ready = ref(false) const cropperImageSrc = ref("") const cropperCanvasRef = ref<InstanceType<typeof CropperCanvas>>() const cropperImageRef = ref<InstanceType<typeof CropperImage>>() const cropperSelectionRef = ref<InstanceType<typeof CropperSelection>>() const handleSelectFile = () => { if (fileInputRef.value) { fileInputRef.value.value = "" fileInputRef.value.click() } } const handleFileChange = (e: Event) => { const target = e.target as HTMLInputElement const file: File = (target.files as FileList)[0] if (!file) { return } cropperImageSrc.value = URL.createObjectURL(file) cropperImageDom.src = URL.createObjectURL(file) ready.value = true } const inSelection = (selection: Selection, maxSelection: Selection) => { return ( selection.x >= maxSelection.x && selection.y >= maxSelection.y && (selection.x + selection.width) <= (maxSelection.x + maxSelection.width) && (selection.y + selection.height) <= (maxSelection.y + maxSelection.height) ) } function onSelectionChange(event: CustomEvent) { // Prevent the default behavior of the selection change event to avoid the cropper from applying the selection immediately. // We want to apply our own constraints instead. if (!cropperCanvasRef.value || !cropperImageRef.value || !cropperSelectionRef.value) { return; } const selection = event.detail as Selection const cropperCanvasRect = cropperCanvasRef.value.getBoundingClientRect(); const cropperImageRect = cropperImageRef.value.getBoundingClientRect(); const width = Math.min(selection.width, cropperImageRect.width); const height = Math.min(selection.height, cropperImageRect.height); const minX = cropperImageRect.x - cropperCanvasRect.x; const minY = cropperImageRect.y - cropperCanvasRect.y; const maxX = minX + cropperImageRect.width - width; const maxY = minY + cropperImageRect.height - height; const x = Math.max(minX, Math.min(selection.x, maxX)); const y = Math.max(minY, Math.min(selection.y, maxY)); cropperSelectionRef.value.x = x; cropperSelectionRef.value.y = y; cropperSelectionRef.value.width = width; cropperSelectionRef.value.height = height; cropperSelectionRef.value.$render(); const maxSelection: Selection = { x: cropperImageRect.left - cropperCanvasRect.left, y: cropperImageRect.top - cropperCanvasRect.top, width: cropperImageRect.width, height: cropperImageRect.height } if (!inSelection(selection, maxSelection)) { cropperSelectionRef.value.x = maxSelection.x; cropperSelectionRef.value.y = maxSelection.y; cropperSelectionRef.value.width = maxSelection.width; cropperSelectionRef.value.height = maxSelection.height; cropperSelectionRef.value.$render(); } }
内容来源: fengyuanchen/cropperjs