css3 – CSS背后的数学背景是什么?

前端之家收集整理的这篇文章主要介绍了css3 – CSS背后的数学背景是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在创建一个“图像生成器”,用户可以上传图像并添加文字和/或绘制图像。输出的图像是固定尺寸(698×450)。

在客户端,当用户上传图像时,将其设置为背景大小为698×450的div的背景。这使得它很好地填满了地区。

最终组合的图像由PHP使用GD函数生成。我的问题是,如何在PHP中以与CSS相同的方式获得图像的扩展。我希望PHP脚本的结果看起来像在CSS中设置的图像一样,就像上面那样。
有人知道浏览器使用background-size:cover如何计算如何适当地缩放图像?我想把它翻译成PHP

谢谢

解决方法

这是覆盖计算背后的逻辑。

您有四个基本值:

  1. imgWidth // your original img width
  2. imgHeight
  3.  
  4. containerWidth // your container width (here 698px)
  5. containerHeight

从这些值得出的两个比值:

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

您想要找到两个新值:

  1. finalWidth // the scaled img width
  2. finalHeight

所以:

  1. if (containerRatio > imgRatio)
  2. {
  3. finalHeight = containerHeight
  4. finalWidth = (containerHeight / imgRatio)
  5. }
  6. else
  7. {
  8. finalWidth = containerWidth
  9. finalHeight = (containerWidth / imgRatio)
  10. }

…你有相当于一个背景大小:封面。

猜你在找的CSS相关文章