在Javascript中旋转图像后获取图像尺寸

3

这篇文章主要讲解与IT技术相关的数学问题。我们有时会遗忘学校学习的知识,这是一件遗憾的事情。

好的,我正在尝试使用Javascript从canvas中获取在特定角度旋转后的图像尺寸。

enter image description here


1
(100+40Math.sqrt(3))(100*Math.sqrt(3)+40) - undefined
3代表什么?角度去哪了? - undefined
2个回答

11

由于我这里除了MSPaint之外没有其他工具,所以我将重用您的图像:

enter image description here

假设原始矩形大小为RW(矩形宽度)* RH(高度),

在这种情况下,RW = 200RH = 80

在逆时针旋转某个角度A之后,

其中度数为0deg <= A <= 90deg(或弧度为0 <= A <= Math.PI/2),

在这种情况下,A=30degA=Math.PI/6

在新的“外部”矩形中,每条边都被分成两个部分(为了方便描述;对应于图像)。

在左侧,假设上部(紫色)称为NHU(New Height Up),下部(红色)称为NHL(New Height Low)。

底边同理,我们有NWL(New Width Left)(蓝色)和NWR(New Width Right)(橙色)。

因此,新矩形的大小(面积)将为(NHU + NHL) * (NWL + NWR)

根据sin和cos的定义:

NWL = RW * Math.cos(A); //where A is in radians
NHL = RW * Math.sin(A);

NHU = RH * Math.cos(A);
NWR = RH * Math.sin(A);
如果您使用度数中的A,请将A替换为Math.PI*A/180

因此,新的“外部”宽度将是NWL + NWR,新的“外部”高度将是NHU + NHL,现在您可以计算一切。


非常感谢您详细的回答。笔误:NWR 应该是 RH * Math.sin(A); - undefined

4
这里有一个插入函数,它实现了@Passerby的解决方案和其他几个保护措施:
function imageSizeAfterRotation(size, degrees) {
    degrees = degrees % 180;
    if (degrees < 0) {
        degrees = 180 + degrees;
    }
    if (degrees >= 90) {
        size = [ size[1], size[0] ];
        degrees = degrees - 90;
    }
    if (degrees === 0) {
        return size;
    }
    const radians = degrees * Math.PI / 180;
    const width = (size[0] * Math.cos(radians)) + (size[1] * Math.sin(radians));
    const height = (size[0] * Math.sin(radians)) + (size[1] * Math.cos(radians));
    return [ width, height ];
}

// USAGE:
imageSizeAfterRotation([ 200, 80 ], 30) // [ 213.20508075688775, 169.28203230275508 ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接