feat:裁剪头像

This commit is contained in:
2026-06-15 10:24:15 +08:00
parent cb8ddd34a1
commit 2ca7bb9817
4 changed files with 433 additions and 33 deletions
@@ -0,0 +1,308 @@
<template>
<view class="avatar-cropper">
<view class="crop-stage">
<view class="crop-box" :style="{ width: cropSizePx + 'px', height: cropSizePx + 'px' }">
<movable-area
class="crop-movable-area"
:style="{ width: cropSizePx + 'px', height: cropSizePx + 'px' }"
v-if="imagePath"
>
<movable-view
class="crop-movable-view"
direction="all"
:x="posX"
:y="posY"
:style="{ width: drawWidthPx + 'px', height: drawHeightPx + 'px' }"
@change="onMoveChange"
>
<image class="crop-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>
</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, 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 cropSizePx = ref(0);
const imagePath = ref('');
const imgWidth = ref(0);
const imgHeight = ref(0);
const coverScale = ref(1);
const drawWidthPx = computed(() => Math.round(imgWidth.value * coverScale.value));
const drawHeightPx = computed(() => Math.round(imgHeight.value * coverScale.value));
const posX = ref(0);
const posY = ref(0);
const clamp = (val, min, max) => Math.min(max, Math.max(min, val));
const calcCoverScale = () => {
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 box = cropSizePx.value;
posX.value = Math.round((box - w) / 2);
posY.value = Math.round((box - h) / 2);
clampPosition();
};
const clampPosition = () => {
const w = drawWidthPx.value;
const h = drawHeightPx.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 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;
coverScale.value = calcCoverScale();
await nextTick();
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: () => {
emit('error', 'chooseImage_failed');
},
});
};
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 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 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;
if (props.src) loadImage(props.src);
});
watch(
() => cropSizePx.value,
() => {
if (!imagePath.value) return;
coverScale.value = calcCoverScale();
nextTick(() => resetPosition());
},
);
</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-box {
position: relative;
background: #000;
border-radius: 18rpx;
overflow: hidden;
}
.crop-movable-area {
background: #000;
}
.crop-movable-view {
position: absolute;
left: 0;
top: 0;
}
.crop-image {
width: 100%;
height: 100%;
}
.crop-frame {
position: absolute;
left: 0;
top: 0;
border: 2rpx solid rgba(255, 255, 255, 0.95);
box-sizing: border-box;
pointer-events: none;
}
.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: rgba(255, 255, 255, 0.16);
color: #ffffff;
border: 2rpx solid rgba(255, 255, 255, 0.25);
}
.btn-primary {
background: #2556ec;
color: #ffffff;
}
.btn-primary.disabled {
opacity: 0.5;
}
.hidden-canvas {
position: absolute;
left: -9999px;
top: -9999px;
}
</style>
+12
View File
@@ -467,6 +467,18 @@
"group": "通用"
}
},
{
"path": "avatarCrop",
"style": {
"navigationBarTitleText": "裁剪头像",
"navigationStyle": "custom"
},
"meta": {
"sync": true,
"title": "裁剪头像",
"group": "通用"
}
},
{
"path": "richtext",
"style": {
+105
View File
@@ -0,0 +1,105 @@
<template>
<s-pages title="裁剪头像" :purple_bg="true">
<view class="avatar-crop-page">
<avatarCropper @confirm="onConfirm" @error="onError" />
<view v-if="uploading" class="loading-mask">
<view class="loading-box">上传中...</view>
</view>
</view>
</s-pages>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { baseUrl } from '@/sheep/config';
import avatarCropper from '@/components/avatar_uploader/avatar_cropper.vue';
const { proxy } = getCurrentInstance();
const uploading = ref(false);
const eventChannel = ref(null);
onLoad(() => {
eventChannel.value = proxy.getOpenerEventChannel ? proxy.getOpenerEventChannel() : null;
});
const uploadAvatar = async (filePath) => {
const token = uni.getStorageSync('token') ? uni.getStorageSync('token') : undefined;
const tenantId = uni.getStorageSync('tenant-id');
const result = await new Promise((resolve, reject) => {
uni.uploadFile({
url: baseUrl + '/app-api/infra/file/upload',
filePath,
name: 'file',
formData: {
directory: 'head',
'tenant-id': tenantId,
token: token,
},
header: {},
success: (res) => resolve(res),
fail: (err) => reject(err),
});
}).catch(() => null);
if (!result) throw new Error('upload_failed');
let data = null;
try {
data = typeof result.data === 'string' ? JSON.parse(result.data) : result.data;
} catch (e) {
throw new Error('upload_parse_failed');
}
const url = data?.data || '';
if (!url) throw new Error('upload_no_url');
return url;
};
const onConfirm = async (croppedFilePath) => {
if (uploading.value) return;
uploading.value = true;
try {
const url = await uploadAvatar(croppedFilePath);
if (eventChannel.value && eventChannel.value.emit) {
eventChannel.value.emit('success', { url });
}
uni.navigateBack();
} catch (e) {
uni.showToast({ title: '上传失败,请重试', icon: 'none' });
} finally {
uploading.value = false;
}
};
const onError = () => {
uni.showToast({ title: '处理失败,请重试', icon: 'none' });
};
</script>
<style lang="scss" scoped>
.avatar-crop-page {
position: relative;
height: 100%;
}
.loading-mask {
position: absolute;
inset: 0;
z-index: 999;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.35);
}
.loading-box {
padding: 18rpx 26rpx;
border-radius: 14rpx;
background: rgba(0, 0, 0, 0.55);
color: #fff;
font-size: 28rpx;
}
</style>
+8 -33
View File
@@ -30,7 +30,6 @@
import { ref, computed, reactive, onMounted } from 'vue';
import AuthUtil from '@/sheep/api/member/auth';
import card_list from '@/components/card_list/card_list.vue';
import { baseUrl } from '@/sheep/config';
import UserApi from '@/sheep/api/member/user';
const appInfo = computed(() => sheep.$store('app').info);
const isLogin = computed(() => sheep.$store('user').isLogin);
@@ -177,38 +176,14 @@
}
const upImg = () => {
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
success: function (res) {
const tempFilePaths = res.tempFilePaths;
const tempFiles = res.tempFiles;
let resSize = tempFiles[0].size;
if (resSize > 1048576) {
uni.showToast({
title: '上传图片大小不能超过1MB',
icon: 'error',
});
return;
}
const token = uni.getStorageSync('token') ? uni.getStorageSync('token') : undefined;
let tenant_id = uni.getStorageSync('tenant-id');
uni.uploadFile({
url: baseUrl + '/app-api/infra/file/upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData: {
directory: 'head',
'tenant-id': tenant_id,
token: token,
},
header: {},
success: (uploadFileRes) => {
let url = JSON.parse(uploadFileRes.data).data;
upData({
avatar: url,
});
},
uni.navigateTo({
url: '/pages/public/avatarCrop',
success: (res) => {
const eventChannel = res?.eventChannel;
if (!eventChannel) return;
eventChannel.on('success', ({ url }) => {
if (!url) return;
upData({ avatar: url });
});
},
});