CSS的背景尺寸背后的数学:封面 [英] What's the math behind CSS's background-size:cover
问题描述
我正在创建一个图像生成器,用户可以上传图像并在其上添加文本和/或绘制。输出的图像是固定大小(698x450)。
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).
在客户端上,当用户上传图片时,将其设置为背景尺寸为698x450的div。
On the client side, when the user uploads their image it is set as the background of a div that's 698x450 with background-size:cover. This makes it fill the area nicely.
最后的组合图像是由PHP使用GD函数生成的。我的问题是,我如何得到的图像在PHP中缩放与在CSS中的方式相同。我想要的PHP脚本的结果看起来是相同的,如果图像设置在CSS,因为它是上面。
有谁知道浏览器如何使用background-size:cover计算如何适当缩放图像?
The final combined image is generated by PHP using GD functions. My question is, how can I get the image to scale in PHP the same way it does in CSS. I want the result of the PHP script to look the same as if the image was set in CSS as it was above. Does anyone know how browsers using background-size:cover calculate how to scale the image appropriately? I want to translate this into PHP.
感谢
推荐答案
您有四个基本值:
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
您要找到两个新值:
finalWidth // the scaled img width
finalHeight
因此:
if (containerRatio > imgRatio)
{
finalHeight = containerHeight
finalWidth = (containerHeight / imgRatio)
}
else
{
finalWidth = containerWidth
finalHeight = (containerWidth / imgRatio)
}
。和你有一个background-size:cover。
... and you have the equivalent of a background-size : cover.
这篇关于CSS的背景尺寸背后的数学:封面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!