vue-cropper官网
链接:https://github.com/xyxiao001/vue-cropper
安装:npm install vue-cropper 或者 yarn add vue-cropper
图片上传的格式我用的是base64格式的,剪裁完的图片格式也同样转成了base64
<template>
<a-modal :visible="visible" title="修改头像" :maskClosable="false" :confirmLoading="confirmLoading" :width="800"
@cancel="cancelHandel">
<a-row>
<a-col :xs="24" :md="12" :style="{height: '350px'}">
<vue-cropper
ref="cropper"
:img="imgUrl"
:info="true"
:autoCrop="options.autoCrop"
:autoCropWidth="options.autoCropWidth"
:autoCropHeight="options.autoCropHeight"
:fixedBox="options.fixedBox"
@realTime="realTime"
>
</vue-cropper>
</a-col>
<a-col :xs="24" :md="12" :style="{height: '350px'}">
<div class="avatar-upload-preview">
<img :src="previews.url" :style="previews.img"/>
</div>
</a-col>
</a-row>
<template slot="footer">
<a-button key="back" @click="cancelHandel">取消</a-button>
<a-button key="submit" type="primary" :loading="confirmLoading" @click="okHandel">保存</a-button>
</template>
</a-modal>
</template>
<script>
import { VueCropper } from 'vue-cropper'
export default {
name:'ImgCropperModal',
components: {
VueCropper
},
data() {
return {
visible: false,
confirmLoading: false,
options: {
img: '',
autoCrop: true,
autoCropWidth: 200,
autoCropHeight: 200,
fixedBox: true
},
previews: {},
};
},
//这里是父组件传过来的base64格式的图片
props: {
imgUrl: {
type: String,
default: undefined
},
},
methods: {
show(){
this.visible = true;
},
close() {
this.visible = false;
},
cancelHandel() {
this.close();
},
okHandel() {
this.$refs.cropper.getCropBlob(async (data) => {
this.blobToDataURL(data,imageUrl => {
this.$emit('uploadImg',imageUrl)//反显回去
this.visible =false
})
})
},
//blob 格式转 base64
blobToDataURL(blob, callback) {
let a = new FileReader();
a.onload = function (e) { callback(e.target.result); }
a.readAsDataURL(blob);
},
realTime(data) {
this.previews = data
}
},
};
</script>
<style scoped>
.avatar-upload-preview {
position: absolute;
top: 50%;
transform: translate(50%, -50%);
width: 180px;
height: 180px;
border-radius: 50%;
box-shadow: 0 0 4px #ccc;
overflow: hidden;
}
img {
width: 100%;
height: 100%;
}
</style>