2 回答
TA贡献1868条经验 获得超4个赞
如果我们单独查看每个维度,很容易看到调整的数学。
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
}
TA贡献1827条经验 获得超8个赞
这是工作示例 https://codepen.io/Kison/pen/JjdaMda
这是源代码
const MAX_HEIGHT = 500;
const MAX_WIDTH = 600;
function getMediaSize(iw, ih) {
let
ratio = 0,
height = ih,
width = iw
;
if (iw > MAX_WIDTH && iw > ih)
{
height = MAX_WIDTH / (iw / ih /* aspect ratio */);
width = MAX_WIDTH;
}
else if (ih > MAX_HEIGHT && ih > iw)
{
width = MAX_HEIGHT / (ih / iw /* aspect ratio */);
height = MAX_HEIGHT;
}
return {
width: Math.round(width),
height: Math.round(height)
}
}
添加回答
举报
