前端业务开发中使用原生js和elementui两种方式实现头像裁切上传的功能
要实现头像裁剪上传的功能,可以使用现成的JavaScript库,例如cropperjs
。以下是使用原生JavaScript和Element UI实现头像裁剪上传的简化示例:
- 安装
cropperjs
和element-ui
(如果还没有安装):
npm install cropperjs element-ui --save
- 在Vue组件中使用
cropperjs
和element-ui
的Upload
组件:
<template>
<div>
<el-upload
action="http://example.com/upload"
:show-file-list="false"
:on-success="onSuccess"
:before-upload="beforeUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<el-button @click="cropImage">裁剪图片</el-button>
</div>
</template>
<script>
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
export default {
data() {
return {
imageUrl: '',
cropper: null,
croppedBlob: null
};
},
methods: {
beforeUpload(file) {
const reader = new FileReader();
reader.onload = (e) => {
const dataURL = e.target.result;
this.initCropper(dataURL);
};
reader.readAsDataURL(file);
return false; // 阻止默认上传行为
},
onSuccess(response, file, fileList) {
// 上传成功后的处理逻辑
},
cropImage() {
if (this.cropper) {
this.croppedBlob = this.cropper.getCroppedBlob();
const formData = new FormData();
formData.append('file', this.croppedBlob, 'avatar.jpg');
// 使用formData进行上传
// axios.post('http://example.com/upload', formData)...
}
},
initCropper(src) {
const image = new Image();
image.src = src;
image.onload = () => {
const cropperContainer = document.createElement('div');
document.body.appendChild(cropperContainer);
this.cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 1,
dragMode: 'crop',
autoCropArea: 1,
movable: false,
resizable: false,
guides: false,
center: false,
highlight: false,
cropBoxMovable: false,
cropBoxResizable: false,
toggleDragModeOnDblclick: false
});
};
}
}
};
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-ic
评论已关闭