在画布上旋转图像

Rotating Image on Canvas

本文关键字:旋转 图像      更新时间:2023-09-26

在我的web应用程序中,我允许用户选择图像。如果图像的高度大于宽度,则将图像旋转270度。

我对旋转图像的理想尺寸感到困惑,因为我以后会保存旋转图像。

例如,如果用户上传一张低分辨率的图片,图片的大小应该是多少?如果用户上传一张高分辨率的图片,图片的大小应该是多少?

我不希望像素失真。有什么好的库可以在客户端旋转图像?或者有什么算法能帮到我吗?

您可以像这样尝试简单的画布方法:

基本上你将在画布上绘制图像,旋转,然后将画布保存到dataUrl

var context = canvas.getContext('2d');
//save the context
//pushes a Matrix on the transformation stack
context.save();
context.translate(x, y); //where to put image (in the canvas)
context.rotate(angle); //angle in degrees (i think...)
context.scale(scale); //optional scale
//rotate around center of image
context.drawImage(bitmap, -image.width / 2, -image.height / 2);
//or rotate around top left corner of image
context.drawImage(image, 0, 0);
//restore the canvas
//pop a matrix off the transformation stack
context.restore();
//now save the canvas to a data url for download or to display in an image object / tag
var data = canvas.toDataUrl();

引用:https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations

https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement

http://html5.litten.com/understanding-save-and-restore-for-the-canvas-context/

可以使用Blob对象方法。将图像转换为blob对象,您可以使用它。我不能帮助编写代码,因为我不太了解blobs。请对blobs做更多的研究,你可以用blobs实现你想要做的事情。