Javascript 根据纵横比将图像大小约束为最大高度和最大宽度

Javascript 根据纵横比将图像大小约束为最大高度和最大宽度,javascript,image,math,Javascript,Image,Math,我有一个名为getMediaSize的函数,它接受图像高度和图像宽度: const MAX_HEIGHT=500 常数最大宽度=600 函数getMediaSize(iw、ih){ } 我希望函数能够根据纵横比返回符合MAX\u width x MAX\u height尺寸的新图像宽度和高度 例如,getMediaSize(1200800)应该返回{w:600,h:400}如果我们单独查看每个维度,很容易看到调整的数学结果 MAX_DIMENSION = CURRENT_DIMENSION *

我有一个名为
getMediaSize
的函数,它接受图像高度和图像宽度:

const MAX_HEIGHT=500
常数最大宽度=600
函数getMediaSize(iw、ih){
}
我希望函数能够根据纵横比返回符合
MAX\u width x MAX\u height
尺寸的新图像宽度和高度


例如,
getMediaSize(1200800)
应该返回
{w:600,h:400}

如果我们单独查看每个维度,很容易看到调整的数学结果

MAX_DIMENSION = CURRENT_DIMENSION * ADJUSTMENT

// We need to figure out what the adjustment is, we have the other two values
// do some algebra and we get
ADJUSTMENT = MAX_DIMENSION / CURRENT_DIMENSION
出现的问题是,每个维度都有自己的调整值,这会导致拉伸/压缩图像(纵横比不保持不变)。所以我们只需要选择一个调整值来使用,但是哪一个呢?当然是最小的,否则其中一个维度将溢出

// Calculate which adjustment is the smallest, width or height
// otherwise we'd overflow one of them.
let widthPercent = MAX_WIDTH / iw;
let heightPercent = MAX_HEIGHT / ih;
let smallestPercent = Math.min(widthPercent, heightPercent);

// This works for both scaling up and scaling down
return {
    w: iw * smallestPercent,
    h: ih * smallestPercent
}

如果我们单独观察每个维度,很容易看到调整的数学模型

MAX_DIMENSION = CURRENT_DIMENSION * ADJUSTMENT

// We need to figure out what the adjustment is, we have the other two values
// do some algebra and we get
ADJUSTMENT = MAX_DIMENSION / CURRENT_DIMENSION
出现的问题是,每个维度都有自己的调整值,这会导致拉伸/压缩图像(纵横比不保持不变)。所以我们只需要选择一个调整值来使用,但是哪一个呢?当然是最小的,否则其中一个维度将溢出

// Calculate which adjustment is the smallest, width or height
// otherwise we'd overflow one of them.
let widthPercent = MAX_WIDTH / iw;
let heightPercent = MAX_HEIGHT / ih;
let smallestPercent = Math.min(widthPercent, heightPercent);

// This works for both scaling up and scaling down
return {
    w: iw * smallestPercent,
    h: ih * smallestPercent
}
下面是一个工作示例

这是源代码

const MAX_HEIGHT=500;
const MAX_WIDTH=600;
函数getMediaSize(iw、ih){
让
比率=0,
高度=ih,
宽度=iw
;  
如果(iw>最大宽度(&iw>ih)
{   
高度=最大宽度/(iw/ih/*纵横比*/);
宽度=最大宽度;
} 
否则如果(ih>最大高度(&ih>iw)
{    
宽度=最大高度/(ih/iw/*纵横比*/);
高度=最大高度;
}
返回{
宽度:数学圆(宽度),
高度:数学圆(高度)
}
}
下面是一个工作示例

这是源代码

const MAX_HEIGHT=500;
const MAX_WIDTH=600;
函数getMediaSize(iw、ih){
让
比率=0,
高度=ih,
宽度=iw
;  
如果(iw>最大宽度(&iw>ih)
{   
高度=最大宽度/(iw/ih/*纵横比*/);
宽度=最大宽度;
} 
否则如果(ih>最大高度(&ih>iw)
{    
宽度=最大高度/(ih/iw/*纵横比*/);
高度=最大高度;
}
返回{
宽度:数学圆(宽度),
高度:数学圆(高度)
}
}