iphone canvas画图选择问题解决

199 阅读1分钟

  handleChooseImg = (e) => {
    return this.chooseImg(e.target.files[0])
  }
  // 图片选择回调
  chooseImg = async (file) => {
    if (!file) {return;}
    let that = this
    const imgOrientation = await new Promise((resolve, reject) => {
      if (EXIF) {
        EXIF.getData(file, function() {
          resolve(EXIF.getTag(this, 'Orientation'))
        });
      }
    })
    const image = await new Promise((resolve, reject) => {
      if (window.FileReader) {
        let fr = new FileReader();
        fr.onloadend = e => {
          var image = new Image();
          image.src = e.target.result;
          image.onload = function () {
            that.setState({
              showUrl: e.target.result,
              widthMax: this.width / this.height > 0.754
            })
            resolve(image)
          }
        };
        fr.readAsDataURL(file);
      } else {
        alert('浏览器不支持图片上传。')
      }
    })
    document.querySelector(".canvasbox").appendChild(this.canvasdraw(image, imgOrientation))
  }
  // canvas 画图
  canvasdraw = (file, imgOrientation) => {
    const cvs = document.createElement('canvas')
    const ctx = cvs.getContext('2d');
    let scale = 1
    cvs.width = file.width;
    cvs.height = file.height;
    if (file && imgOrientation && imgOrientation !== 1){
      switch(imgOrientation){
        case 6:     // 旋转90度
          cvs.width = file.height * scale;
          cvs.height = file.height * scale;
          ctx.rotate(Math.PI / 2);
          ctx.drawImage(file, 0,-file.height * scale,  file.width * scale, file.height * scale);
          break;
        case 3:     // 旋转180度
          ctx.rotate(Math.PI);
          ctx.drawImage(file, file.height * scale, -file.height * scale,  file.width * scale, file.height * scale);
          break;
        case 8:     // 旋转-90度
          cvs.width = file.height * scale;
          cvs.height = file.height * scale;
          ctx.rotate(3 * Math.PI / 2);
          ctx.drawImage(file, - file.height * scale, 0,  file.width * scale, file.height * scale);
          break;
        default:
          break;
      }
    }
    //  安卓没有Orientation信息, 或者Orientation信息 === 1 表示 iOS横拍,默认画图
    file && (!imgOrientation || imgOrientation === 1) && ctx.drawImage(file, 0, 0)
    cvs.style.backgroundColor = '#FF0000';
    return cvs
  }