vue-cropper裁剪网络照片跨域

问题描述:将网络照片传给vue-cropper时,报跨域问题,导致图片无法显示

错误信息

解决方案:前提条件 图片服务器允许跨域

     1 获取网络照片地址

 getImgUrl(url, showFodder) {
      if (url) {
        this.setImgBase64(url, base64 => {
          this.$nextTick(() => {
            this.showFodder.status = showFodder.status
            const index = showFodder.index
            // 提取size
            const fitmentIndex = this.productOption.fitmentIndex
            let tempArr = this.productTempArr[fitmentIndex]
            let tempIndex = this.productOption.indexArr[fitmentIndex].index
            let temp = tempArr[tempIndex]
            let module = temp.module[index]
            if (module.code) {
              let size = []
              size.push(module.code.width)
              size.push(module.code.height)
              this.showFodder.size = size
              this.showFodder.autoCropWidth = size[0]
              this.showFodder.autoCropHeight = size[1]
              this.showFodder.url = base64
              if (this.showFodder.url) {
                this.showFodder.cropper = true
              }
            }
          })
        })
      }
    },

2 设置需要展示的图片,将图片转为base64,否则报跨域问题,我之前就是因为这个原因报的跨域

// 将网络图片转换成base64格式
    transBase64FromImage(image) {
      let canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      let ctx = canvas.getContext('2d')
      ctx.drawImage(image, 0, 0, image.width, image.height)
      // 可选其他值 image/jpeg
      return canvas.toDataURL('image/jpeg')
    },
    // 设置需要展示的图片  base64
    setImgBase64(src, callback) {
      let _this = this
      let image = new Image()
      // 处理缓存
      image.src = src + '?v=' + Math.random()
      // 支持跨域图片
      image.crossOrigin = '*'
      image.onload = function() {
        let base64 = _this.transBase64FromImage(image)
        callback && callback(base64)
      }
    },

3 显示裁剪框,开始裁剪并获取裁剪后的照片地址

​
// 获取裁剪图片
    getCropperInfo(url, showFodder) {
      if (url) {
        const index = parseInt(showFodder.index)
        // 当前操作模块
        const fitmentIndex = this.productOption.fitmentIndex
        let tempArr = this.productTempArr[fitmentIndex]
        let tempIndex = this.productOption.indexArr[fitmentIndex].index
        let temp = tempArr[tempIndex]
        let module = temp.module[index]
        module.code.img = url
        temp.module.splice(index, 1, module)
        this.initProduct()
      }
    },

​

4 把数据提交到服务器

参考地址:https://blog.csdn.net/Ton555555/article/details/111337934

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值