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)
}
}
添加回答
舉報