在画布上旋转图像

时间:2014-08-13 07:51:10

标签: javascript jquery html5-canvas

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

我对旋转图像的理想大小感到困惑,因为我稍后会保存旋转的图像。

例如,如果用户上传的分辨率较低的图像应该是那么大小的图像,如果用户上传的图像具有高转速,那么大小会是多少?

我不想让像素失真。任何好的库在客户端旋转图像?或者任何可以帮助我的算法?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以尝试这样天真的画布方法:

基本上你将在画布上绘制图像,旋转,然后将画布保存到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/