css - 为什么 `svg` 大小和圆圈 `stroke-width` 与预期不符?

标签 css svg

谷歌浏览器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/

相关文章:

html - 如何证明CSS表格单元格的合理性?

JavaScript 最大表格大小

html - 将一个 div 放在谷歌地图上?

javascript - SVG `<path>` javascript 动画未按预期工作

html - 如何在 opencart 2.0.1.1 中的奖励积分通知电子邮件中应用 css 样式?

javascript - 从该窗口本身控制浏览器窗口(顶部窗口而不是弹出窗口)的高度和宽度

javascript - 如何将两个 SVG 路径组合在一起(不带空格)

html - 停止时 SGV 梯度变暗

javascript - 如何使用 D3.js 更改轴上显示的数据

javascript - 高度 : auto calculating incorrectly if element is hidden when dom loads, 然后稍后显示