安装使用
yarn add vue-cropper
组件内引入:
import { VueCropper } from 'vue-cropper'
components: {
VueCropper
}
全局引入:
import VueCropper from 'vue-cropper'
Vue.use(VueCropper)
相关代码如下:
<string-dialog-form v-model="show" :confirm-loading="confirmLoading" :title="title" centered width="620px" @cancel="onCancel" @ok="onSubmit">
<div class="cropper-content">
<div class="cropper" style="text-align: center">
<vueCropper
ref="cropper"
:autoCrop="option.autoCrop"
:autoCropHeight="option.autoCropHeight"
:autoCropWidth="option.autoCropWidth"
:canMove="option.canMove"
:canMoveBox="option.canMoveBox"
:centerBox="option.centerBox"
:fixed="option.fixed"
:fixedBox="option.fixedBox"
:fixedNumber="option.fixedNumber"
:full="option.full"
:img="option.img"
:info="true"
:infoTrue="option.infoTrue"
:original="option.original"
:outputSize="option.size"
:outputType="option.outputType"
/>
</div>
</div>
</string-dialog-form>
import { VueCropper } from 'vue-cropper';
import { stringGetFilePreviewUrl, UploadFile } from 'string-framework/api/file';
import { DownloadRequest } from 'string-framework/api';
import { public_string2object } from 'string-framework/utils/util.public';
export default {
components: {
VueCropper
},
data() {
return {
title: '裁剪图标',
show: false,
data: {},
confirmLoading: false,
option: {
canMove: true,
img: '', // 裁剪图片的地址
info: true, // 裁剪框的大小信息
outputSize: 1, // 裁剪生成图片的质量
outputType: 'png', // 裁剪生成图片的格式
canScale: true, // 图片是否允许滚轮缩放
autoCrop: true, // 是否默认生成截图框
canMoveBox: true, // 截图框能否拖动
autoCropWidth: 200, // 默认生成截图框宽度
autoCropHeight: 200, // 默认生成截图框高度
fixedBox: false, // 固定截图框大小 不允许改变
fixed: true, // 是否开启截图框宽高固定比例
fixedNumber: [1, 1], // 截图框的宽高比例
full: false, // 是否输出原图比例的截图
original: false, // 上传图片按照原始比例渲染
centerBox: false, // 截图框是否被限制在图片里面
infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
},
fileName: ''
};
},
methods: {
getFileUrl() {
if (this.data.url) {
if (this.data.url.substr(0, 4) == 'http' || this.data.url.indexOf('base64') > -1) {
return this.data.url;
}
return stringGetFilePreviewUrl(this.data.url);
}
return '';
},
open(data) {
this.show = true;
this.data = data;
this.$set(this.option, 'img', this.getFileUrl(data.url));
this.fileName = data.fileName;
},
// 提交
onSubmit() {
// 获取截图的 blob 数据
this.$refs.cropper.getCropBlob(data => {
const file = new File([data], this.fileName, { type: data.type });
// 创建 FormData 对象
const formData = new FormData();
// 将 File 添加到 FormData 中
formData.append('file', file);
DownloadRequest.post(UploadFile, formData)
.then(res => {
if (res.type === 'application/json') {
const reader = new FileReader();
reader.readAsText(res);
reader.onload = evt => {
const resultObj = public_string2object(evt.target.result);
this.$emit('uploadFile', resultObj.data);
this.onCancel();
this.$message.success(resultObj.message);
};
}
})
.catch(err => {
console.log(err);
});
});
},
// 取消
onCancel() {
this.show = false;
}
}
.cropper-content {
.cropper {
width: auto;
height: 350px;
}
}