美文网首页
vue裁剪图片 ,兼容ie11

vue裁剪图片 ,兼容ie11

作者: 小码农_影 | 来源:发表于2021-03-24 11:36 被阅读0次
     <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(){//上传图片按钮触发的事件
                const input = document.getElementById(this.id)
                // 解决同一个文件不能监听的问题
                input.addEventListener(
                    'click',
                    function() {
                        this.value = ''
                    },
                    false
                )
                // 点击input
                input.click()
            },
           handleFilesUpload(e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length) return;
                let index = files[0].name.lastIndexOf('.'); //获取最后一个.的索引
                let exName = files[0].name.substring(index + 1, files[0].name.length);//后缀名
                exName = exName.toLowerCase();//文件后缀名转成小写
                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(){//缩小图片只改变滑块的距离就可以,因为在watch中统一对图片处理
                this.value3 = this.value3 - 20;
            },
            scaleBigger(){//放大图片只改变滑块的距离就可以,因为在watch中统一对图片处理
                this.value3 = this.value3 + 20;
            },
            handleScroll (e) {//监听鼠标滚轮事件
                var direction = e.deltaY>0?'down':'up' //该语句可以用来判断滚轮是向上滑动还是向下
                if(direction == 'down'&& this.value3>=0){//滚轮向下滚动,缩小图片,监听滚轮的目的是为了和下面的slider联动,5为步长
                    this.value3 = this.value3 - 20;
                }else if(direction == 'up' && this.value3<=100){//滚轮向上滚动,放大图片
                    this.value3 = this.value3 + 20;
                }
            },
            rotate(){//旋转
                this.cropper.rotate(90);
            },
    

    效果:


    image.png

    相关文章

      网友评论

          本文标题:vue裁剪图片 ,兼容ie11

          本文链接:https://www.haomeiwen.com/subject/opgchltx.html