在画布上旋转图像时遇到麻烦

问题描述

我正在尝试使用画布旋转图像。 但是,当绘制图像时,尺寸会被裁剪,而我不会裁剪图像。 这是什么样子。 原始图像。

Original Image

旋转图像。

enter image description here

这是我尝试过的。

 function ImageRotate({file})
  const getRotatedImg = (degree) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext('2d');


    // draw the image
    // since the context is rotated,the image will be rotated also
    const img = new Image();
    img.src = file.src;
    canvas.width = img.width;
    canvas.height = img.height;

    // move to the center of the canvas
    ctx.translate(img.width / 2,img.height / 2);

    // rotate the canvas to the specified degrees
    ctx.rotate(degree * Math.PI / 180);
    ctx.drawImage(img,-img.width / 2,-img.height / 2);

    // we’re done with the rotating so restore the unrotated context
    return new Promise((resolve,reject) => {
      canvas.toBlob(blob => {
        if (!blob) {
          //reject(new Error('Canvas is empty'));
          console.error('Canvas is empty');
          return;
        }

        blob.name = file.name;
        resolve(blob);
      },file.type);
    });
  }
  
   const onRotateRight = async () => {
    const rotatedImageUrl = await getRotatedImg(90);
    // this will change file.src by converting rotatedImageURL to a base64string.
    onRotateImage(index,rotatedImageUrl)
  }
  
  return (<div>
    <img style={ImageStyle} src={file.src}/>
     <i class="fa fa-shield fa-rotate-90 mr-3" title="rotate" onClick={() => { onRotateRight() }}></i>
    </div>);
  
  }

这是我组件的代码段。谁能帮我理解为什么这张照片被裁剪了。对于正方形图像,它可以正常工作,而矩形图像不能按预期工作。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)