【发布时间】:2022-01-20 22:44:14
【问题描述】:
我有一个显示图像的简单 html。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Image Object Fit</title>
<style>
body {
margin: 0;
width: 100vw;
height: 100vh;
}
img {
width: 100%;
height: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<img src="https://placekitten.com/200/300" alt="" />
</body>
</html>
https://jsbin.com/hapoqog/edit?html,output
img 元素具有不同的属性:width,height,offsetWidth,offsetHeight,naturalWidth,naturalHeight,但它们都没有正确给出渲染图像的尺寸。
如何计算渲染图像的宽度、高度和缩放/缩放?
【问题讨论】:
-
当我们有 Stack Snippets 时不需要 jsbin 链接(图标在编辑器工具栏上看起来像
<>)。 -
我认为这将是一些简单的数学问题。
naturalWidth和naturalHeight获取原始宽度和高度(200 和 300)。因此,将宽度除以高度以获得纵横比。然后将其乘以当前高度以获得当前渲染宽度(因为纵横比 1 时,我会留给你做什么。
标签: html css image browser object-fit