我知道这是一个非常古老的问题,但是我写的答案实际上更干净,因为它在图像之间使用最大值和最小值比率而不是每个图像本身:
var originalRatios = {
width: containerWidth / imageNaturalWidth,
height: containerHeight / imageNaturalHeight
};
var coverRatio = Math.max(originalRatios.width, originalRatios.height);
var newImageWidth = imageNaturalWidth * coverRatio;
var newImageHeight = imageNaturalHeight * coverRatio;
我喜欢这种方法,因为它非常系统化——也许这并不是一个正确的词语——我的意思是你可以摆脱if
语句,并以更加"数学公式"的方式使其工作(即输入=输出,如果有意义的话):
var ratios = {
cover: function(wRatio, hRatio) {
return Math.max(wRatio, hRatio);
},
contain: function(wRatio, hRatio) {
return Math.min(wRatio, hRatio);
},
"auto": function() {
return 1;
},
"100% 100%": function(wRatio, hRatio) {
return { width:wRatio, height:hRatio };
}
};
function getImageSize(options) {
if(!ratios[options.size]) {
throw new Error(options.size + " not found in ratios");
}
var r = ratios[options.size](
options.container.width / options.image.width,
options.container.height / options.image.height
);
return {
width: options.image.width * (r.width || r),
height: options.image.height * (r.height || r)
};
}
使用方法
const { width, height } = getImageSize({
container: {width: 100, height: 100},
image: {width: 200, height: 50},
size: 'cover'
});
操场
我在这里创建了一个jsbin
,如果您想看看我的“系统化”是什么意思(它还具有一个scale
方法,我认为在此答案中不需要,但对于一些其他事情非常有用)。
finalHeight = (containerWidth * imgRatio)
才能使我的代码正常工作。 - ErgecimgRatio
是height / width
。我们需要将height / width
乘以width
来得到height
。@mddw,请修正你的答案。 - George