大家好,
我正在尝试编写一个JavaScript函数,它将扩展图像以始终填充div(因此根据需要裁剪顶部或侧面).这是CSS等效的CSS3代码background-size:cover.
我不能为我的生活弄清楚.这是我到目前为止:
function full_bleed(box_width, box_height, new_width, new_height)
{
var aspect_ratio=new_width/new_height;
if(new_height<box_height) {
new_height=box_height;
new_width=Math.round(new_height*aspect_ratio);
}
if(new_width<box_width) {
new_width=box_width;
new_height=Math.round(new_width/aspect_ratio);
}
return {
width: new_width,
height: new_height
};
}
我想你们其中一个人可能会有这个等式.
谢谢!
解决方法:
感谢Ben的评论,我明白了.
full_bleed: function(boxWidth, boxHeight, imgWidth, imgHeight)
{
// Calculate new height and width
var initW = imgWidth;
var initH = imgHeight;
var ratio = initH / initW;
imgWidth = boxWidth;
imgHeight = boxWidth * ratio;
if(imgHeight < boxHeight){
imgHeight = boxHeight;
imgWidth = imgHeight / ratio;
}
// Return new size
return {
width: imgWidth,
height: imgHeight
};
}