vue+cropperjs 前端上传图片在对话框中裁剪

517 阅读1分钟
<input type="file" id="uploads" value="imgFile"
accept="image/png, image/jpeg, image/gif, image/jpg"
@change="uploadImg($event)" style="display:none" />

uploadImg(e) {
      var _this = this
      //上传图片
      var file = e.target.files[0]
      _this.fileName = file.name
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        return false
      }
      let imgFile = new FileReader()
      imgFile.readAsDataURL(file)
      imgFile.onload = (res) => {
        _this.cropImgUrl = res.target.result
        _this.$refs.crop.dialogVisible = true
        _this.$nextTick(() => {
          _this.$refs.crop.init()
        })
      }
    }
    
<img id="image" :src="cropImgUrl" alt="Picture" />


this.cropper = new Cropper(image, {
        aspectRatio: 1,
        background: false,
        dragMode: 'move',
        viewMode: 1,
        center: true,
        cropBoxMovable: false, // 是否通过拖拽来移动剪裁框
        cropBoxResizable: false, // 是否通过拖动来调整剪裁框的大小
        ready: () => {
          this.cropper.zoomTo(1) // 需要图片以原比例展示
          this.cropper.setCropBoxData({
            top: 75,
            left: 75,
            width: 300,
            height: 300
          }) // 设置裁剪框的大小和位置
        }
      })