实现: vue按比例裁剪图片
安装:npm i vue-cropper
全局引入:(main.js)
import VueCropper from 'vue-cropper'
Vue.use(VueCropper)
代码实例:
<div class="one-form-item"> <el-upload class="avatar-uploader" action :auto-upload="false" :on-change="uploadFileMethodAnswer" :show-file-list="false" :multiple="true" :before-upload="beforeAvatarUpload" > <el-button class="uploader-button" type="primary">上传banner图</el-button> <span> (建议分辨率800*450)</span> </el-upload> </div>
<el-dialog title="图片剪裁(为确保剪切后图片的分辨率足够,请尽量不缩放剪切原图)" :visible.sync="dialogVisible" append-to-body width="70%" style="margin-top: -8vh"> <div class="cropper-content"> <div class="cropper" style="text-align:center"> <vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" :fixedBox="option.fixedBox" :fixed="option.fixed" :fixedNumber="option.fixedNumber" ></vueCropper> </div> </div> <div slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="finish" :loading="loading">确认</el-button> </div> </el-dialog> </el-dialog>
option配置:(参考网站)
https://www.npmjs.com/package/vue-cropper/v/0.4.7
https://github.com/fengyuanchen/cropperjs#options
option: { img: "", outputSize: 1, //剪切后的图片质量(0.1-1) full: false, //输出原图比例截图 props名full outputType: "png", canMove: true, original: false, canMoveBox: true, autoCrop: true, autoCropWidth: 868, autoCropHeight: 488, fixedBox: false, fixed: true, maxImgSize: 3000, // 图片最大像素 fixedNumber: [16, 9] },
提交数据(js)
finish() { let _this = this; this.$refs.cropper.getCropBlob(data => { let base64Data = null; let a = new FileReader(); a.onload = function(e) { base64Data = e.target.result; _this.loading = true; const formData = new FormData(); formData.append("imageFile", base64Data); uploadImg({ formData: formData }) .then(res => { }) .catch(() => { // this.$message.error('图片上传失败!'); }); }; a.readAsDataURL(data); }); },
.cropper-content { .cropper { width: auto; height: 500px!important; } }