vue裁剪圖片 ,兼容ie11

 <div style="width:540px;height:280px;margin: 0 auto" id="copper">
        <img id="image" :src="url" style="max-width:100%;max-height:100%;margin:0 auto;" />
  </div>
  <div style="width: 540px;margin: 0 auto;display: flex;justify-content: space-between;height: 30px;margin-top: 21px">
     <el-button @click="uploadImgBtn">上傳圖片</el-button>
      <i  @click="scaleSmaller" class=" iconfont m-r-10 ic-sml scaleBtn" style="vertical-align: top"></i>
     <el-slider v-model="value3" :step="20"  :show-tooltip="false" class="slider"></el-slider>
     <i @click="scaleBigger"  class=" iconfont m-r-10 ic-big scaleBtn" style="vertical-align: top"></i>
     <i class=" iconfont m-r-10 vertical-middle ic-turn scaleBtn" @click="rotate"></i>
  </div>
 <div class="btn-save">
      <el-button v-if="showCropper" @click="crop">保存</el-button>
  </div>
<input type="file" :id="id" ref="files" @change="handleFilesUpload($event)" style="display: none"
                               accept="image/jpeg"/>

 import Cropper from "cropperjs";
  uploadImgBtn(){//上傳圖片按鈕觸發(fā)的事件
            const input = document.getElementById(this.id)
            // 解決同一個(gè)文件不能監(jiān)聽的問題
            input.addEventListener(
                'click',
                function() {
                    this.value = ''
                },
                false
            )
            // 點(diǎn)擊input
            input.click()
        },
       handleFilesUpload(e) {
            let files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;
            let index = files[0].name.lastIndexOf('.'); //獲取最后一個(gè).的索引
            let exName = files[0].name.substring(index + 1, files[0].name.length);//后綴名
            exName = exName.toLowerCase();//文件后綴名轉(zhuǎn)成小寫
            if(Math.ceil(files[0].size / 1024) > 1000) { //圖片超出了1M,不允許上傳
                this.fixedMessage('照片大小不能超過1M','error');//打開message
                return;
            }
            this.showCropper = true;
            this.picValue = files[0];
            this.url = this.getObjectURL(this.picValue);
            //每次替換圖片要重新得到新的url
            if (this.cropper) {
                this.cropper.replace(this.url);
            }
        },
        getObjectURL(file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        },
        crop() {
            var croppedCanvas;
            var roundedCanvas;
            if (!this.croppable) {
                return;
            }
            croppedCanvas = this.cropper.getCroppedCanvas();
            roundedCanvas = this.getRoundedCanvas(croppedCanvas);
            this.headerImage = roundedCanvas.toDataURL("image/jpg", 0.8);
            let blob= this.dataURLtoFile( this.headerImage);
            this.uploadCover(blob);
        },
        dataURLtoFile(dataURI,filename='file'){
            var arr = dataURI.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n),
                suffix = mime.split('/')[1];
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            let theBlob = new Blob([u8arr],{type:mime});
            theBlob.lastModifiedDate = new Date();
            theBlob.name = `${filename}.${suffix}`;
            return {
                file:theBlob,
                name:`${filename}.${suffix}`
            }
        },
        getRoundedCanvas(sourceCanvas) {
            var canvas = document.createElement("canvas");
            var context = canvas.getContext("2d");
            var width = sourceCanvas.width;
            var height = sourceCanvas.height;
            canvas.width = width;
            canvas.height = height;
            context.imageSmoothingEnabled = true;
            context.drawImage(sourceCanvas, 0, 0, width, height);
            context.beginPath();
            context.fill();
            return canvas;

        },
        // 保存上傳功能
        uploadCover(fileData) {
            var that = this;
            let formData = new FormData();
            formData.append('file', fileData.file,fileData.name);
            formData.append('personName',this.GLOBAL.global.personName);
            formData.append('idType',this.GLOBAL.global.idType);
            formData.append('idNo',this.GLOBAL.global.idNo);
            formData.append('telephone',this.GLOBAL.global.telephone);
            formData.append('companyCode',this.GLOBAL.global.companyCode);
            that.savePhoto(formData)
        },
        savePhoto(formData){//上傳圖片接口
            var that = this;
            this.loading = true;
            axios({
                method: 'post',
                url: process.env.VUE_APP_API_BASE + '/signature/app/addPersonSeals',
                data:formData,
                headers: {
                    'Content-Type': "multipart/form-data",
                    'Authorization': this.GLOBAL.global.access_token
                }
            }).then(res=>{
                this.loading = false;
                if(res.data.success){
                    if(res.data.success){
                        this.openMessage('添加印章成功','success','vo-ui');//打開message
                    }
                }else{
                    this.fixedMessage(res.data.errorMsg,'error')
                }
            }).catch((error)=>{
                this.loading = false;
                this.fixedMessage(error,'error')
            })
        },
     scaleSmaller(){//縮小圖片只改變滑塊的距離就可以,因?yàn)樵趙atch中統(tǒng)一對圖片處理
            this.value3 = this.value3 - 20;
        },
        scaleBigger(){//放大圖片只改變滑塊的距離就可以,因?yàn)樵趙atch中統(tǒng)一對圖片處理
            this.value3 = this.value3 + 20;
        },
        handleScroll (e) {//監(jiān)聽鼠標(biāo)滾輪事件
            var direction = e.deltaY>0?'down':'up' //該語句可以用來判斷滾輪是向上滑動還是向下
            if(direction == 'down'&& this.value3>=0){//滾輪向下滾動,縮小圖片,監(jiān)聽滾輪的目的是為了和下面的slider聯(lián)動,5為步長
                this.value3 = this.value3 - 20;
            }else if(direction == 'up' && this.value3<=100){//滾輪向上滾動,放大圖片
                this.value3 = this.value3 + 20;
            }
        },
        rotate(){//旋轉(zhuǎn)
            this.cropper.rotate(90);
        },

效果:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容