Full Bleed Image Resize Calculation

前端 未结 2 1248
既然无缘
既然无缘 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:49

    Thanks to the comment from Ben, I figured it out.

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

提交回复
热议问题