调整图像大小并将画布旋转90度

时间:2017-05-19 18:37:29

标签: javascript canvas rotation

这里有很多关于在js上使用canvas旋转图像的主题。我读了大部分内容,无法找到解决问题的方法。

我正在接收任何分辨率的图像(来自上传组件)。我正在将其调整为1024x768,如:

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");

if (img.width >= img.height) {
    canvas.width = 1024;
    canvas.height = 768;
} else {
    canvas.width = 768;
    canvas.height = 1024;
}
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);   

工作正常。

但是在Safari / iO上,当我拍照并上传时,图像的宽度值始终高于高度,因此上面的代码不起作用。

所以我决定使用exif-js来检测图像的方向。当Orientation属性高于4时,我需要将图像旋转90度,并交换高度和宽度值。

我试图像这样旋转图像:

canvas.width = 768; // swapping values
canvas.height = 1024;                                       

ctx.translate(canvas.width/2, canvas.height/2);  // translate to center
ctx.rotate(Math.PI/2); // rotate 90 degrees

ctx.drawImage(img, -img.width/2,-img.height/2); // not sure of the dx and dy values here... 

图像旋转。但它只占原始图像的一小部分才能显示在画布上,因此感觉“放大”......似乎我在drawImage方法上使用了错误的值,但不确定如何修复。

如何使用固定的高度和宽度值修复此旋转?

1 个答案:

答案 0 :(得分:2)

在新画布上顺时针旋转90度。

const canvas = document.createElement("canvas");
canvas.width = image.height;
canvas.height = image.width;
const ctx = canvas.getContext("2d");
ctx.setTransform(
     0,1, // x axis down the screen
    -1,0, // y axis across the screen from right to left
    image.height, // x origin is on the right side of the canvas 
    0             // y origin is at the top
);
ctx.drawImage(image,0,0);
ctx.setTransform(1,0,0,1,0,0); // restore default

如果您需要缩放图像以适合大小(假设图像将旋转)

const width = 1024; // after rotation
const height = 768; // after rotation
const scale = width / image.height; // how much to scale the image to fit
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const  ctx = canvas.getContext("2d");
ctx.setTransform(
     0,scale, // x axis down the screen
    -scale,0, // y axis across the screen from right to left
    width,    // x origin is on the right side of the canvas 
    0         // y origin is at the top
);
ctx.drawImage(image,0,0);
ctx.setTransform(1,0,0,1,0,0); // restore default