谷歌浏览器60.0.3112.90
我学习 SVG。为什么svg
真实尺寸不是10cm x 10cm,圆笔触宽度
不是1pt 和半径
不是2.5cm?
.svg-container, .canvas{
margin: 0;
padding: 0;
width: 10cm;
height: 10cm;
background-color: green;
}
.geometry {
stroke: gray;
fill: yellow;
stroke-width: 1px;
}
<div class='svg-container'>
<svg class='canvas' viewBox='0 0 10 10'>
<circle class='geometry' cx='5' cy='5'
r='2.5'/>
</svg>
</div>
最佳答案
首先:never trust the browser to generate true physical sizes specified in stylesheets on the screen .
请注意,您已将 viewBox 声明为 0 0 10 10
,这意味着它的宽度为 10 个单位,高度为 10 个单位。应用于其中的 SVG 元素的所有单位都将相对于 viewBox 尺寸进行渲染,即 stroke-width: 1px
圆上的内容将渲染为 viewBox 宽度的 1/10。拿走viewBox
属性将强制以绝对像素渲染事物。
在下面的示例中,我将 svg 宽度设置为 200px
出于说明目的。当viewBox="0 0 10 10"
使用时,所有单位都将相对于该尺寸进行测量:
- 笔画宽度 1 像素意味着 (200 ÷ 10) × 1 = 20 像素
- 半径
2.5
意味着 (200 ÷ 10) × 2.5 = 50px
只要记住当 viewBox
它设置后,它控制如何在自己的坐标系中设置内容:并且根据 <svg>
的宽度和高度放大/缩小到屏幕上的实际像素。元素。这里提供了更好的解释:svg viewBox attribute
.svg-container, .canvas{
margin: 0;
padding: 0;
width: 200px;
height: 200px;
background-color: green;
}
.geometry {
stroke: gray;
fill: yellow;
stroke-width: 1px;
}
<div class='svg-container'>
<!-- Viewbox forces all units to be relative to its dimensions -->
<svg class='canvas' viewBox='0 0 10 10'>
<circle class='geometry' cx='5' cy='5'
r='2.5'/>
</svg>
</div>
<br />
<div class='svg-container'>
<!-- Without viewbox, all units are rendered in px -->
<svg class='canvas'>
<circle class='geometry' cx='50' cy='50'
r='25'/>
</svg>
</div>
关于css - 为什么 `svg` 大小和圆圈 `stroke-width` 与预期不符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45719592/