猿问

根据纵横比将图像大小限制为最大高度和最大宽度

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


const MAX_HEIGHT = 500

const MAX_WIDTH = 600

function getMediaSize(iw, ih) {


}

我希望该函数MAX_WIDTH x MAX_HEIGHT根据纵横比返回适合尺寸的新图像宽度和高度。


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


冉冉说
浏览 164回答 2
2回答

MYYA

如果我们单独查看每个维度,很容易看到调整的数学。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 getADJUSTMENT = 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 downreturn {    w: iw * smallestPercent,    h: ih * smallestPercent}

慕仙森

这是工作示例 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)  }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答