<template>
<el-dialog
:close-on-click-modal="false"
title="提示"
:visible="dialogVisible"
width="500px"
@close="showdialog"
class="cropperCss"
>
<div class="hello">
<div style="margin-right: 20px">
<div style="text-align: center; margin-bottom: 20px; color: #fff">
预览
</div>
<div class="before"></div>
</div>
<div class="container">
<div class="img-container">
<img :src="srcUrlImg" ref="image" />
</div>
</div>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="showdialog">取 消</el-button>
<el-button type="primary" @click="sureSava">确 定</el-button>
</span>
</el-dialog>
</template>
vue2代码
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs"; 这两个必须要引入
<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { userAvatar } from "@/api/vipSign";
export default {
props: ["dialogVisible"],
data() {
return {
myCropper: null,
afterImg: "",
srcUrlImg: null,
};
},
methods: {
init() {
this.$nextTick(() => {
if (this.myCropper) {
this.myCropper.destroy();
}
this.myCropper = new Cropper(this.$refs.image, {
// viewMode: 1,
// dragMode: "none",
// initialAspectRatio: 1,
// aspectRatio: 1,
preview: ".before",
// background: false,
// autoCropArea: 0.6,
// zoomOnWheel: false,
viewMode: 1, // 只能在裁剪的图片范围内移动
dragMode: "move", // 画布和图片都可以移动
aspectRatio: 1, // 裁剪区默认正方形
autoCropArea: 0.6, // 自动调整裁剪图片
cropBoxMovable: true, // 禁止裁剪区移动
cropBoxResizable: true, // 禁止裁剪区缩放
background: true, // 关闭默认背景
});
});
},
async sureSava() {
const canvas = this.myCropper.getCroppedCanvas(); // 获取裁剪后的canvas对象
canvas.toBlob(async (blob) => {
try {
await userAvatar(blob); // 将图片发送到服务器 blob格式
this.$store.dispatch("app/getUser"); // 这里重新调用 用户信息接口用于页面上所有显示头像的地方一起更换
} catch (error) {
console.log(error);
}
});
this.showdialog();
},
showdialog() {
this.$emit("showdialog");
},
},
mounted() {},
updated() {
this.init();
},
};
</script>
css 样式 可按ui原型自行更改
<style scoped lang="scss">
.cropperCss {
display: flex;
justify-content: center;
align-items: center;
}
.hello {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 40px;
}
.cropper-container {
width: 300px !important;
height: 300px !important;
}
.container {
// display: flex;
width: 250px;
height: 250px;
}
.before {
width: 100px;
height: 100px;
overflow: hidden;
border-radius: 100%;
/* 这个属性可以得到想要的效果 */
}
.img-container {
height: 250px;
overflow: hidden;
}
.afterCropper {
flex: 1;
margin-left: 20px;
border: 1px solid salmon;
text-align: center;
}
.afterCropper img {
width: 150px;
margin-top: 30px;
}
.dialog-footer {
display: flex;
justify-content: center;
align-items: center;
}
</style>