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

Javascript 调整图像大小并将画布旋转90度,javascript,canvas,rotation,Javascript,Canvas,Rotation,这里有很多关于在js上使用画布旋转图像的主题。我读了其中的大部分,却找不出解决问题的办法 我正在接收一个上传组件的图像,无论分辨率如何。我正在将其调整为1024x768,如: var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); if (img.width >= img.height) { canvas.width = 1024; canvas.height =

这里有很多关于在js上使用画布旋转图像的主题。我读了其中的大部分,却找不出解决问题的办法

我正在接收一个上传组件的图像,无论分辨率如何。我正在将其调整为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/iOs上,当我拍照并上传时,图像的宽度值总是比高度值高,所以上面的代码不起作用

所以我决定使用exif js来检测图像的方向。当方向属性大于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方法上使用了错误的值,但不确定如何修复


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

在新画布上顺时针旋转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

非常感谢。重绘和缩放是缺少的关键点。它工作得很好。@blindman67我使用了你的解决方案,它几乎对我有效,只是它剪切了我的一些图像。我在这里问了我的问题,如果可以请帮忙。非常感谢。