我正在开发一个网络应用程序,现在面临着一项相当棘手的任务。 我有一张图片,我必须为其添加叠加层。
假设我有一张汽车图片。我需要在汽车图片上添加值,例如外部和内部温度。
为这些温度标签添加固定像素偏移很容易,但图像需要可缩放到每个屏幕高度和宽度方向。我想不出简单的方法来将 div 缩放为与“background-size:contain;”完全相同的 div。用于图像。
在我编写复杂的 JavaScript 缩放逻辑之前,有人可以指出正确的轨道吗?
最佳答案
ww = window width
wh = window height
ow = Original Width of your image
oh = Original Height of your image
nw = New Width of your image
nh = New Height of your image
mt = Margin top to adjust image to the screen vertically
ox = overlay location x coordinate according to original size of the image
oy = overlay location y coordinate according to original size of the image
nox = New ox
noy = new oy
sf = scaling factor
根据屏幕尺寸,您将拥有图像的缩放比例。
sf = ww / ow -> we find our scaling factor
nh = oh * sf -> then calculate our new image height
mt = (oh - nh) / 2 -> amount we need to shift image up to center screen
nox = ox * sf -> new overlay x coordinate
noy = (oy * sf) - mt -> new overlay y coordinate
编辑
如果图像太宽则需要调整此逻辑以水平而不是垂直移动图像
编辑2
如果您只针对现代浏览器,那么您可以使用 CSS
transform: scale(sx[, sy]);
。这将重新调整您的 DIV
及其所有内容的大小 使用 transform: scale()
with transform-origin: 0 0;
从左上角调整大小。
关于javascript - 将 div 缩放为像背景图像一样的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28682903/