利用Canvas下载旋转后的图片

105 阅读1分钟
downloadByCanvas = () => {
    const canvas = document.getElementById('canvasImg');
    const ctx = canvas.getContext('2d');
    const imgObj = new Image();
    const _that = this;
    imgObj.src = this.state.src;
    imgObj.crossOrigin = 'anonymous';

    imgObj.onload = function() {
      canvas.width = this.naturalWidth;
      canvas.height = this.naturalHeight;
      const width = this.naturalWidth;
      const height = this.naturalHeight;
      if ([90, 180, 270].includes(_that.state.rotate)) {
        const mapA = {
          90: 1,
          180: 2,
          270: 3
        };
        const angle = mapA[_that.state.rotate];// 旋转角度 1:90度,2:180度,3:270
        console.log(angle, '----->angle');
        if (angle === 0) {
          canvas.height = canvas.width * height / width;
          ctx.drawImage(imgObj, 0, 0, canvas.width, canvas.height);
        } else if (angle === 1 || angle === 3) {
          canvas.height = canvas.width * width / height;
          ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
          angle === 1 ? ctx.rotate(0.5 * Math.PI) : ctx.rotate(1.5 * Math.PI);
          ctx.drawImage(imgObj, -canvas.height / 2, -canvas.width / 2, canvas.height, canvas.width);
        } else {
          canvas.height = canvas.width * height / width;
          ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
          ctx.rotate(1 * Math.PI);
          ctx.drawImage(imgObj, -canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);
        }
      } else {
        const width = this.naturalWidth;
        const height = this.naturalHeight;
        canvas.height = canvas.width * height / width;
        ctx.drawImage(imgObj, 0, 0, canvas.width, canvas.height);
      }
      // setTimeout(() => {
      const rotatedImageURL = canvas.toDataURL('image/png');
      const downloadLink = document.createElement('a');
      downloadLink.href = rotatedImageURL;
      downloadLink.download = 'rotated_image.png';
      downloadLink.click();
      // }, 3000);
    };
  }
  • imgObj.crossOrigin = 'anonymous'跨域的图片不能下载
  • 等比例缩放图片
  • 旋转角度的处理