實現: vue按比例裁剪圖片vue
安裝:npm i vue-croppergit
全局引入:(main.js)github
<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配置:(參考網站)npm
https://www.npmjs.com/package/vue-cropper/v/0.4.7app
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)this
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; } }