feat: 裁剪添加放大缩小

This commit is contained in:
2026-06-15 11:02:13 +08:00
parent 8ec0ad482b
commit 104d63a73d
2 changed files with 256 additions and 40 deletions
+238 -40
View File
@@ -1,33 +1,54 @@
<template>
<view class="avatar-cropper">
<view class="crop-stage">
<view class="crop-box" :style="{ width: cropSizePx + 'px', height: cropSizePx + 'px' }">
<view
ref="stageEl"
class="crop-stage"
@touchstart="onTouchStart"
@touchmove="onTouchMove"
@touchend="onTouchEnd"
@touchcancel="onTouchEnd"
@wheel.stop.prevent="onWheel"
@mousewheel.stop.prevent="onWheel"
>
<view class="crop-stage-inner">
<movable-area
class="crop-movable-area"
:style="{ width: cropSizePx + 'px', height: cropSizePx + 'px' }"
v-if="imagePath"
class="stage-area"
:style="{ width: stageWidthPx + 'px', height: stageHeightPx + 'px' }"
>
<movable-view
class="crop-movable-view"
class="stage-movable"
direction="all"
:out-of-bounds="true"
:x="posX"
:y="posY"
:style="{ width: drawWidthPx + 'px', height: drawHeightPx + 'px' }"
@change="onMoveChange"
>
<image class="crop-image" :src="imagePath" mode="scaleToFill" />
<image class="stage-image" :src="imagePath" mode="scaleToFill" />
</movable-view>
</movable-area>
<view v-else class="empty-state flex-center" @click="chooseImage">
<view class="empty-btn">选择图片</view>
</view>
<view class="crop-frame" :style="{ width: cropSizePx + 'px', height: cropSizePx + 'px' }"></view>
<view v-if="imagePath" class="mask-layer" :style="{ width: stageWidthPx + 'px', height: stageHeightPx + 'px' }">
<view class="mask-top" :style="{ height: cropTopPx + 'px' }"></view>
<view class="mask-middle" :style="{ height: cropSizePx + 'px' }">
<view class="mask-left" :style="{ width: cropLeftPx + 'px' }"></view>
<view class="mask-hole" :style="{ width: cropSizePx + 'px', height: cropSizePx + 'px' }"></view>
<view class="mask-right" :style="{ width: stageWidthPx - cropLeftPx - cropSizePx + 'px' }"></view>
</view>
<view class="mask-bottom" :style="{ height: stageHeightPx - cropTopPx - cropSizePx + 'px' }"></view>
<view class="crop-border" :style="{ left: cropLeftPx + 'px', top: cropTopPx + 'px', width: cropSizePx + 'px', height: cropSizePx + 'px' }"></view>
</view>
</view>
</view>
<view class="actions">
<view class="btn btn-ghost" @click="chooseImage">重新选择</view>
<view class="btn btn-primary" :class="{ disabled: !imagePath }" @click="confirmCrop">确定裁剪</view>
<view class="btn btn-primary" :class="{ disabled: !imagePath }" @click="confirmCrop">确认</view>
</view>
<canvas
@@ -39,7 +60,7 @@
</template>
<script setup>
import { ref, computed, nextTick, getCurrentInstance, onMounted, watch } from 'vue';
import { ref, computed, nextTick, getCurrentInstance, onMounted, onUnmounted, watch } from 'vue';
const props = defineProps({
src: {
@@ -57,21 +78,33 @@
const outputSizePx = computed(() => Number(props.outputSize) || 600);
const stageEl = ref(null);
const stageDomEl = ref(null);
const cropSizePx = ref(0);
const stageWidthPx = ref(0);
const stageHeightPx = ref(0);
const imagePath = ref('');
const imgWidth = ref(0);
const imgHeight = ref(0);
const coverScale = ref(1);
const baseScale = ref(1);
const zoom = ref(1);
const minZoom = 1;
const maxZoom = 4;
const drawWidthPx = computed(() => Math.round(imgWidth.value * coverScale.value));
const drawHeightPx = computed(() => Math.round(imgHeight.value * coverScale.value));
const totalScale = computed(() => (baseScale.value || 1) * (zoom.value || 1));
const drawWidthPx = computed(() => Math.ceil(imgWidth.value * totalScale.value));
const drawHeightPx = computed(() => Math.ceil(imgHeight.value * totalScale.value));
const posX = ref(0);
const posY = ref(0);
const clamp = (val, min, max) => Math.min(max, Math.max(min, val));
const calcCoverScale = () => {
const cropLeftPx = computed(() => Math.max(0, Math.round((stageWidthPx.value - cropSizePx.value) / 2)));
const cropTopPx = computed(() => Math.max(0, Math.round((stageHeightPx.value - cropSizePx.value) / 2)));
const calcBaseScale = () => {
if (!cropSizePx.value || !imgWidth.value || !imgHeight.value) return 1;
const sw = cropSizePx.value / imgWidth.value;
const sh = cropSizePx.value / imgHeight.value;
@@ -81,20 +114,40 @@
const resetPosition = () => {
const w = drawWidthPx.value;
const h = drawHeightPx.value;
const left = cropLeftPx.value;
const top = cropTopPx.value;
const box = cropSizePx.value;
posX.value = Math.round((box - w) / 2);
posY.value = Math.round((box - h) / 2);
posX.value = Math.round(left + box / 2 - w / 2);
posY.value = Math.round(top + box / 2 - h / 2);
clampPosition();
};
const clampPosition = () => {
const w = drawWidthPx.value;
const h = drawHeightPx.value;
const left = cropLeftPx.value;
const top = cropTopPx.value;
const box = cropSizePx.value;
const minX = Math.round(box - w);
const minY = Math.round(box - h);
posX.value = clamp(posX.value, minX, 0);
posY.value = clamp(posY.value, minY, 0);
const minX = Math.round(left + box - w);
const maxX = Math.round(left);
const minY = Math.round(top + box - h);
const maxY = Math.round(top);
posX.value = clamp(posX.value, minX, maxX);
posY.value = clamp(posY.value, minY, maxY);
};
const measureStage = async () => {
const rect = await new Promise((resolve) => {
uni
.createSelectorQuery()
.in(proxy)
.select('.crop-stage-inner')
.boundingClientRect((r) => resolve(r))
.exec();
}).catch(() => null);
if (!rect) return;
stageWidthPx.value = Math.max(1, Math.round(Number(rect.width) || 0));
stageHeightPx.value = Math.max(1, Math.round(Number(rect.height) || 0));
};
const loadImage = async (src) => {
@@ -115,8 +168,10 @@
imagePath.value = src;
imgWidth.value = Number(info.width) || 0;
imgHeight.value = Number(info.height) || 0;
coverScale.value = calcCoverScale();
zoom.value = 1;
baseScale.value = calcBaseScale();
await nextTick();
await measureStage();
resetPosition();
};
@@ -129,9 +184,7 @@
if (!filePath) return;
await loadImage(filePath);
},
fail: () => {
emit('error', 'chooseImage_failed');
},
fail: () => {},
});
};
@@ -142,15 +195,92 @@
clampPosition();
};
const pinchState = ref({
active: false,
startDist: 0,
startZoom: 1,
});
const getTouchDist = (touches) => {
if (!touches || touches.length < 2) return 0;
const t1 = touches[0];
const t2 = touches[1];
const dx = Number(t2.clientX) - Number(t1.clientX);
const dy = Number(t2.clientY) - Number(t1.clientY);
return Math.sqrt(dx * dx + dy * dy);
};
const onTouchStart = (e) => {
const touches = e?.touches || [];
if (touches.length !== 2) return;
pinchState.value = {
active: true,
startDist: getTouchDist(touches),
startZoom: zoom.value,
};
};
const onTouchMove = (e) => {
const touches = e?.touches || [];
if (!pinchState.value.active || touches.length !== 2) return;
const dist = getTouchDist(touches);
if (!dist || !pinchState.value.startDist) return;
const nextZoom = clamp(pinchState.value.startZoom * (dist / pinchState.value.startDist), minZoom, maxZoom);
if (Math.abs(nextZoom - zoom.value) < 0.001) return;
applyZoom(nextZoom);
};
const onTouchEnd = () => {
pinchState.value.active = false;
};
const onWheel = (e) => {
if (!imagePath.value) return;
let dy = 0;
if (typeof e?.deltaY === 'number' && e.deltaY) {
dy = e.deltaY;
} else if (typeof e?.detail?.deltaY === 'number' && e.detail.deltaY) {
dy = e.detail.deltaY;
} else if (typeof e?.wheelDelta === 'number' && e.wheelDelta) {
dy = -e.wheelDelta;
} else if (typeof e?.detail?.wheelDelta === 'number' && e.detail.wheelDelta) {
dy = -e.detail.wheelDelta;
} else if (typeof e?.detail === 'number' && e.detail) {
dy = e.detail;
}
if (!dy) return;
const factor = dy > 0 ? 0.92 : 1.08;
applyZoom(clamp(zoom.value * factor, minZoom, maxZoom));
};
const applyZoom = (nextZoom) => {
if (!imagePath.value) return;
const prevScale = totalScale.value || 1;
const nextScale = (baseScale.value || 1) * (nextZoom || 1);
const left = cropLeftPx.value;
const top = cropTopPx.value;
const box = cropSizePx.value;
const centerX = left + box / 2;
const centerY = top + box / 2;
const imgX = (centerX - posX.value) / prevScale;
const imgY = (centerY - posY.value) / prevScale;
zoom.value = nextZoom;
posX.value = Math.round(centerX - imgX * nextScale);
posY.value = Math.round(centerY - imgY * nextScale);
nextTick(() => clampPosition());
};
const confirmCrop = async () => {
if (!imagePath.value) return;
clampPosition();
await nextTick();
const box = cropSizePx.value;
const scale = coverScale.value || 1;
const sx = Math.max(0, Math.round((-posX.value / scale) * 1000) / 1000);
const sy = Math.max(0, Math.round((-posY.value / scale) * 1000) / 1000);
const left = cropLeftPx.value;
const top = cropTopPx.value;
const scale = totalScale.value || 1;
const sx = Math.max(0, Math.round(((left - posX.value) / scale) * 1000) / 1000);
const sy = Math.max(0, Math.round(((top - posY.value) / scale) * 1000) / 1000);
const sWidth = Math.min(imgWidth.value, Math.round((box / scale) * 1000) / 1000);
const sHeight = Math.min(imgHeight.value, Math.round((box / scale) * 1000) / 1000);
@@ -188,15 +318,54 @@
cropSizePx.value = Math.floor(w * 0.78);
if (cropSizePx.value < 220) cropSizePx.value = 220;
if (cropSizePx.value > 360) cropSizePx.value = 360;
nextTick(() => measureStage());
if (props.src) loadImage(props.src);
const el = stageEl.value?.$el || stageEl.value;
stageDomEl.value = el || null;
if (el && typeof el.addEventListener === 'function') {
const handler = (evt) => {
try {
evt.preventDefault && evt.preventDefault();
evt.stopPropagation && evt.stopPropagation();
} catch (e) {}
onWheel(evt);
};
el.__avatarCropWheelHandler = handler;
el.addEventListener('wheel', handler, { passive: false });
el.addEventListener('mousewheel', handler, { passive: false });
}
});
onUnmounted(() => {
const el = stageDomEl.value || stageEl.value?.$el || stageEl.value;
const handler = el && el.__avatarCropWheelHandler;
if (el && handler && typeof el.removeEventListener === 'function') {
el.removeEventListener('wheel', handler);
el.removeEventListener('mousewheel', handler);
try {
delete el.__avatarCropWheelHandler;
} catch (e) {}
}
});
watch(
() => cropSizePx.value,
() => {
if (!imagePath.value) return;
coverScale.value = calcCoverScale();
nextTick(() => resetPosition());
baseScale.value = calcBaseScale();
nextTick(() => {
measureStage();
resetPosition();
});
},
);
watch(
() => [stageWidthPx.value, stageHeightPx.value, zoom.value],
() => {
if (!imagePath.value) return;
nextTick(() => clampPosition());
},
);
</script>
@@ -221,35 +390,64 @@
justify-content: center;
}
.crop-box {
.crop-stage-inner {
width: 100%;
height: 100%;
position: relative;
background: #000;
border-radius: 18rpx;
overflow: hidden;
}
.crop-movable-area {
background: #000;
}
.crop-movable-view {
.stage-area {
position: relative;
background: #000;
}
.stage-movable {
position: absolute;
left: 0;
top: 0;
}
.crop-image {
.stage-image {
width: 100%;
height: 100%;
}
.crop-frame {
.mask-layer {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
}
.mask-top,
.mask-bottom {
width: 100%;
background: rgba(0, 0, 0, 0.45);
}
.mask-middle {
width: 100%;
display: flex;
flex-direction: row;
}
.mask-left,
.mask-right {
height: 100%;
background: rgba(0, 0, 0, 0.45);
}
.mask-hole {
background: transparent;
}
.crop-border {
position: absolute;
border: 2rpx solid rgba(255, 255, 255, 0.95);
box-sizing: border-box;
pointer-events: none;
}
.empty-state {
@@ -286,9 +484,9 @@
}
.btn-ghost {
background: rgba(255, 255, 255, 0.16);
color: #ffffff;
border: 2rpx solid rgba(255, 255, 255, 0.25);
background: transparent;
color: rgba(153, 153, 153, 1);
border: 2rpx solid rgba(220, 220, 220, 1);
}
.btn-primary {