【问题标题】:Why is my SVG line blurry or 2px in height when I specified 1px?当我指定 1px 时,为什么我的 SVG 线条模糊或高度为 2px?
【发布时间】:2019-02-16 07:55:49
【问题描述】:

我正在使用 SVG 创建一条线,但它在我的网页中显得模糊。更清楚地说,它看起来比笔画宽度大 1px。为什么会发生这种情况,有没有办法在 SVG 中修复它?

这里是代码。当我自己运行这段代码时,它并不模糊。当它在我的网页中时,这条线的高度似乎约为 2px,而不是 1。

#HorizontalLine1178  {
	stroke:rgb(154,154,154);
	stroke-width:1;
}
<svg style="width:100%;">
    <line id="HorizontalLine1178" y2="97" y1="97" x2="100%" x1="62" >
</svg>

【问题讨论】:

标签: svg


【解决方案1】:

因为当它的 Y 坐标位于整个像素上时,1px 笔画在它周围,因此“抗锯齿”(请参阅​​ Paul LeBeau 的 excellent illustration)。在这种情况下使用半像素坐标,或者应用 shape-rendering="crispEdges" 它将为您进行像素舍入,但即使在圆形对象上也会产生锐利的边缘:

<svg style="width:100%; background-color: white" stroke="black" fill="white" stroke-width="1">
	<line y2="10.0" y1="10.0" x2="90%" x1="10">
		<title>.0</title>
	</line>
	<line y2="15.5" y1="15.5" x2="90%" x1="10">
		<title>.5</title>
	</line>
	<line y2="20.0" y1="20.0" x2="90%" x1="10" shape-rendering="crispEdges">
		<title>.0 + crispEdges</title>
	</line>

	<circle cy="50" cx="20" r="10">
		<title>.0</title>
	</circle>
	<circle cy="49.5" cx="44.5" r="10">
		<title>.5</title>
	</circle>
	<circle cy="50" cx="70" r="10" shape-rendering="crispEdges">
		<title>.0 + crispEdges</title>
	</circle>

	<rect x="90" y="40" width="20" height="20">
		<title>.0</title>
	</rect>
	<rect x="120" y="40" width="20" height="20" shape-rendering="crispEdges">
		<title>.0 + crispEdges</title>
	</rect>
	<rect x="149.5" y="39.5" width="20" height="20">
		<title>.5</title>
	</rect>

	<rect x="190" y="40" width="20" height="20" stroke="none" fill="black">
		<title>.0 + fill, no stroke</title>
	</rect>
	<rect x="219.5" y="39.5" width="20" height="20" stroke="none" fill="black">
		<title>.5 + fill, no stroke</title>
	</rect>
</svg>

【讨论】:

  • 很好的例子。因此,如果我提前知道笔画的高度为 1px(水平线)并且垂直位置是奇数,“81”而不是“80”,那么我应该将该 y 位置更改为“81.5”以保持线 1px身高?
  • 没有看到您的更新。 crispEdges 设置看起来很棒。为什么你让 Line 没有填充?他们默认有填充吗?
  • 非奇数/偶数:对于笔画,请记住它们是在围绕线连接给定坐标的线中渲染的,并且整个坐标表示像素边界。请参阅 Pauls 在链接问题中的回答,它更好地描述了它。广告fill for line: 不,只是将它砸到选择器中以影响rects。
  • Whole-pixel 坐标在其他方面适用于无描边填充形状(参见示例中的最后一个正方形)。
  • 如果你像我一样喜欢这个答案——但你对自己说,“嘿,我的 SVG 中肯定有很多额外的字符,我正在努力保持小!" -- 然后试着把它放在你打开的&lt;svg&gt;标签之后,记得在&lt;/svg&gt;之前关闭它:&lt;g shape-rendering="crispEdges"&gt;。以这种方式适用于每个对象,并真正改进了我的工作。