Full Bleed Image Resize Calculation

前端 未结 2 1244
既然无缘
既然无缘 2021-02-06 16:09

I am trying to write a JavaScript function that will expand an image to fill a div always (so crop top or sides as needed). It is the JavaScript equivalent of the CSS3 code back

2条回答
  •  感情败类
    2021-02-06 16:47

    I made some changes on Drew's solution to better fit my needs.

    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]);
    

    The idea is the same, but the point here is to calculate the scaled up size without having an initial size of the media, instead using a given aspect ratio. I use it for video embeds, rather than images, where I load the video via YouTube API, for example, and I don't have any initial size, but I know the ratio and I want to stretch the video across the available space. (Of course, it can be changed back to calculate the ratio from the actual dimensions of the video or image.) Also made some code simplifications.

提交回复
热议问题