What's the math behind CSS's background-size:cover

前端 未结 4 1382
长发绾君心
长发绾君心 2021-01-30 13:57

I\'m creating an \"image generator\" where users can upload an image and add text and/or draw on it. The outputted image is a fixed size (698x450).

On the client side,

4条回答
  •  自闭症患者
    2021-01-30 14:42

    Here's a logic behind cover calculations.

    You have four base values :

    imgWidth // your original img width
    imgHeight
    
    containerWidth // your container  width (here 698px)
    containerHeight
    

    Two ratios derived from these values :

    imgRatio = (imgHeight / imgWidth)       // original img ratio
    containerRatio = (containerHeight / containerWidth)     // container ratio
    

    You want to find two new values :

    finalWidth // the scaled img width
    finalHeight
    

    So :

    if (containerRatio > imgRatio) 
    {
        finalHeight = containerHeight
        finalWidth = (containerHeight / imgRatio)
    } 
    else 
    {
        finalWidth = containerWidth 
        finalHeight = (containerWidth / imgRatio)
    }
    

    ... and you have the equivalent of a background-size : cover.

提交回复
热议问题