如何解决在画布上旋转图像时遇到麻烦
我正在尝试使用画布旋转图像。 但是,当绘制图像时,尺寸会被裁剪,而我不会裁剪图像。 这是什么样子。 原始图像。
这是我尝试过的。
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 举报,一经查实,本站将立刻删除。