【问题标题】:Full Bleed Image Resize Calculation全出血图像调整大小计算
【发布时间】:2011-07-20 22:50:05
【问题描述】:

我正在尝试编写一个 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
        };
    
    }

我想你们中的一个人可能有这个等式。

【问题讨论】:

  • 你应该查看 bgStretcher 的来源(或者直接使用它),它本质上就是这样做的(虽然与整个窗口相关联)ajaxblender.com/…

标签: javascript resize crop


【解决方案1】:

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

}

【讨论】:

  • 我知道我不应该只是说“谢谢”,而是男人!!,我一直在查看不同的 jquery 插件,并做了一些“如果宽度 > 高度”,反之亦然,并且一直在尝试为 2 天的视频背景实现正确的配给!!你的解决方案非常简单,我在 2 分钟内实现了,瞧,终于!太棒了,我真的很感激这个,想知道为什么没有更多的选票......真的谢谢你=)
【解决方案2】:

我对 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 加载视频,并且我没有任何初始大小,但我知道比率并且我想在可用空间中拉伸视频。 (当然也可以改回来根据视频或图片的实际尺寸计算比例。) 还做了一些代码简化。

【讨论】:

  • 我喜欢这个主意。如果您提前知道比率,那就太好了。
猜你喜欢
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
  • 2011-03-20
  • 2015-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多