【问题标题】:Why the `svg` size and the circle `stroke-width` are not like expected?为什么 `svg` 大小和圆圈 `stroke-width` 不像预期的那样?
【发布时间】:2017-08-16 17:21:51
【问题描述】:

谷歌浏览器 60.0.3112.90

我学习 SVG。为什么svg real 尺寸不是10cm x 10cm,圆圈stroke-width 不是1ptradius 不是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>

【问题讨论】:

    标签: css svg


    【解决方案1】:

    首先: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" 时,所有单位都将相​​对于该维度进行测量:

    • 1px 的描边宽度表示 (200 &div; 10) × 1 = 20px
    • 2.5 的半径表示 (200 &div; 10) × 2.5 = 50px

    请记住,当viewBox 设置时,它控制内容在其自己的坐标系中的设置方式:并且根据&lt;svg&gt; 的宽度和高度,将其放大/缩小为屏幕上的实际像素元素。这里提供了更好的解释: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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-07
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2019-06-28
      相关资源
      最近更新 更多