全幅图像调整尺寸计算

4

我正在尝试编写一个JavaScript函数,将图像扩展到始终填充一个div(因此根据需要裁剪顶部或侧面)。这是CSS3代码background-size: cover的JavaScript等效代码。

我无论如何都想不出来。目前为止我有以下代码:

    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
        };
    
    }

我想你们其中一个人可能已经有这个方程式了。

3
你应该查看 bgStretcher 的源代码(或直接使用它),这个插件的基本功能是拉伸网页背景图片(虽然它会涉及整个窗口),这里是它的链接:http://www.ajaxblender.com/bgstretcher-jquery-stretch-background-plugin.html。 - Ben
2个回答

4
感谢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
    };

}

1
我知道仅仅说“谢谢”是不够的,但是天啊!!我一直在查找不同的jQuery插件,并且进行一些“if width > Height”和反之操作,尝试了2天才能实现视频背景的正确比例!而你的解决方案非常简单,我只用了2分钟就实现了,终于成功了!所以,我真的很感激你,不知道为什么这个解决方案没有更多的赞...真的非常感谢你=) - Edward

0

我对Drew的解决方案进行了一些修改,以更好地适应我的需求。

function calculateCover(frame, sides) {
    var ratio = sides[1] / sides[0],
        cover = { 
            width: frame.width,
            height: Math.ceil(frame.width * ratio) 
        };

    if (cover.height <= frame.height) {
        cover.height = frame.height;
        cover.width = Math.ceil(frame.height / ratio);
    }

    return cover;
}

calculateCover({width: 1280, height: 822}, [16,9]);

这个想法是一样的,但重点在于计算放大后的尺寸,而不需要媒体的初始尺寸,而是使用给定的宽高比。我将其用于视频嵌入,而不是图像,例如通过YouTube API加载视频,我没有任何初始尺寸,但我知道比例并希望将视频拉伸到可用空间中。(当然,可以改回从实际视频或图像尺寸计算比例。)还进行了一些代码简化。


我喜欢这个想法。如果你事先知道比例就更好了。 - Drew Baker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接