【问题标题】:Resize image and rotate canvas 90 degrees调整图像大小并将画布旋转 90 度
【发布时间】:2017-10-19 23:41:00
【问题描述】:

这里有很多关于在 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 来检测图像的方向。当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 方法上使用了错误的值,但不知道如何修复。

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

【问题讨论】:

    标签: javascript canvas rotation


    【解决方案1】:

    在新画布上顺时针旋转 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 我使用了你的解决方案,它几乎对我有用,除了它削减了我的一些图像。我在这里问了我的问题,如果可以的话,请帮忙。非常感谢。 stackoverflow.com/questions/57896390/…
    猜你喜欢
    • 2015-12-28
    • 2023-03-22
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    相关资源
    最近更新 更多