如何防止 SVG 线条的粗细不一致和间隙?

How to prevent inconsistent thickness and gaps in SVG lines?

我的用例可能有点独特,但我正在使用 DOM 元素封装在 flexbox 中创建一个动态大小的方形网格。每个 DOM 元素都有一个 SVG 图像背景和一个 height/width 等于 calc(100vmin / <gridSize>)。 SVG 元素很简单:

<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"> <path stroke-width="2" stroke="#000" stroke-linecap="square" d="M0,50 h100 M50,0 v50"/> </svg>

但是,我注意到有些线条看起来比其他线条更暗,并且一些 SVG 线条之间存在间隙。 (见下图)我假设这是由于像素四舍五入,因为当我调整浏览器大小时,间隙和厚度会跳来跳去。

我试图从 calc 舍入像素,但我使用的是 styled-components,所以我无法使用 SASS / LESS 函数,如 floor / ceil。我还注意到使笔划宽度变粗可以缓解这个问题,但我更愿意让我的线条变细。

还有其他方法可以使线条保持一致吗?

它是抗锯齿的。设置 shape-rendering="crispEdges" 将在大多数 UA 上关闭它。

vector-effect='non-scaling-stroke'

non-scaling-stroke

This value modifies the way an object is stroked. Normally stroking involves calculating stroke outline of the shapeʼs path in current user coordinate system and filling that outline with the stroke paint (color or gradient). The resulting visual effect of this value is that the stroke width is not dependent on the transformations of the element (including non-uniform scaling and shear transformations) and zoom level.

MDN web docs