Files

507 lines
14 KiB
Vue

<template>
<view class="avatar-cropper">
<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
v-if="imagePath"
class="stage-area"
:style="{ width: stageWidthPx + 'px', height: stageHeightPx + 'px' }"
>
<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="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 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>
<canvas
canvas-id="avatarCropCanvas"
class="hidden-canvas"
:style="{ width: outputSizePx + 'px', height: outputSizePx + 'px' }"
/>
</view>
</template>
<script setup>
import { ref, computed, nextTick, getCurrentInstance, onMounted, onUnmounted, watch } from 'vue';
const props = defineProps({
src: {
type: String,
default: '',
},
outputSize: {
type: Number,
default: 600,
},
});
const emit = defineEmits(['confirm', 'error']);
const { proxy } = getCurrentInstance();
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 baseScale = ref(1);
const zoom = ref(1);
const minZoom = 1;
const maxZoom = 4;
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 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;
return Math.max(sw, sh);
};
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(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(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) => {
if (!src) return;
const info = await new Promise((resolve, reject) => {
uni.getImageInfo({
src,
success: resolve,
fail: reject,
});
}).catch(() => null);
if (!info) {
emit('error', 'getImageInfo_failed');
return;
}
imagePath.value = src;
imgWidth.value = Number(info.width) || 0;
imgHeight.value = Number(info.height) || 0;
zoom.value = 1;
baseScale.value = calcBaseScale();
await nextTick();
await measureStage();
resetPosition();
};
const chooseImage = () => {
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
success: async (res) => {
const filePath = res?.tempFilePaths?.[0] || '';
if (!filePath) return;
await loadImage(filePath);
},
fail: () => {},
});
};
const onMoveChange = (e) => {
if (!e?.detail) return;
posX.value = Math.round(Number(e.detail.x) || 0);
posY.value = Math.round(Number(e.detail.y) || 0);
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 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);
const ctx = uni.createCanvasContext('avatarCropCanvas', proxy);
ctx.clearRect(0, 0, outputSizePx.value, outputSizePx.value);
ctx.drawImage(imagePath.value, sx, sy, sWidth, sHeight, 0, 0, outputSizePx.value, outputSizePx.value);
ctx.draw(false, () => {
uni.canvasToTempFilePath(
{
canvasId: 'avatarCropCanvas',
width: outputSizePx.value,
height: outputSizePx.value,
destWidth: outputSizePx.value,
destHeight: outputSizePx.value,
fileType: 'jpg',
quality: 0.92,
success: (res) => {
const tempFilePath = res?.tempFilePath || '';
if (!tempFilePath) {
emit('error', 'canvasToTempFilePath_empty');
return;
}
emit('confirm', tempFilePath);
},
fail: () => emit('error', 'canvasToTempFilePath_failed'),
},
proxy,
);
});
};
onMounted(() => {
const sys = uni.getSystemInfoSync();
const w = Number(sys.windowWidth) || 375;
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;
baseScale.value = calcBaseScale();
nextTick(() => {
measureStage();
resetPosition();
});
},
);
watch(
() => [stageWidthPx.value, stageHeightPx.value, zoom.value],
() => {
if (!imagePath.value) return;
nextTick(() => clampPosition());
},
);
</script>
<style lang="scss" scoped>
.avatar-cropper {
width: 100%;
height: 100%;
box-sizing: border-box;
padding: 30rpx 32rpx 40rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
.crop-stage {
width: 100%;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.crop-stage-inner {
width: 100%;
height: 100%;
position: relative;
border-radius: 18rpx;
overflow: hidden;
background: #000;
}
.stage-area {
position: relative;
background: #000;
}
.stage-movable {
position: absolute;
left: 0;
top: 0;
}
.stage-image {
width: 100%;
height: 100%;
}
.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;
}
.empty-state {
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.65);
}
.empty-btn {
padding: 18rpx 28rpx;
border-radius: 999rpx;
background: rgba(255, 255, 255, 0.18);
color: #fff;
font-size: 28rpx;
}
.actions {
width: 100%;
display: flex;
gap: 24rpx;
margin-top: 28rpx;
}
.btn {
flex: 1;
height: 84rpx;
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 30rpx;
font-weight: 600;
box-sizing: border-box;
}
.btn-ghost {
background: transparent;
color: rgba(153, 153, 153, 1);
border: 2rpx solid rgba(220, 220, 220, 1);
}
.btn-primary {
background: #2556ec;
color: #ffffff;
}
.btn-primary.disabled {
opacity: 0.5;
}
.hidden-canvas {
position: absolute;
left: -9999px;
top: -9999px;
}
</style>