javascript - 将 div 缩放为像背景图像一样的 div

标签 javascript html css image scale

我正在开发一个网络应用程序,现在面临着一项相当棘手的任务。 我有一张图片,我必须为其添加叠加层。

假设我有一张汽车图片。我需要在汽车图片上添加值,例如外部和内部温度。

为这些温度标签添加固定像素偏移很容易,但图像需要可缩放到每个屏幕高度和宽度方向。我想不出简单的方法来将 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/

相关文章:

javascript - 通过管道而不是 websocket 连接 Puppeteer 的优点和缺点是什么

html - 用 Flex 填充父级的高度

html - CSS 网格正方形布局

html - 将下拉框内的文本对齐到中间

javascript - 菜单图标根据 HTML 类/属性更改颜色

javascript - 访问文件数据时出现问题

javascript - require.js 有时不触发回调函数

python - 为什么在我使用 Google App Engine 呈现 html 文件后我的 html 文件中没有处理我的 css 命令?

javascript - 防止整页在 load() 时向上滚动

javascript - 在第三个文本框中实时显示两个文本框的内容