问题描述
我希望能够将 SVG 元素上的笔触宽度设置为像素感知",无论当前应用的缩放转换如何,它始终为 1px 宽.我知道这很可能是不可能的,因为 SVG 的全部意义在于与像素无关.
I would like to be able to set the stroke-width on an SVG element to be "pixel-aware", that is always be 1px wide regardless of the current scaling transformations applied. I am aware that this may well be impossible, since the whole point of SVG is to be pixel independent.
上下文如下:
我有一个 SVG 元素,它设置了 viewBox 和 preserveAspectRatio 属性.看起来像这样
I have an SVG element with its viewBox and preserveAspectRatio attributes set. It looks something like this
<svg version="1.1" baseProfile="full"
viewBox="-100 -100 200 200" preserveAspectRatio="xMidYMid meet"
xmlns="http://www.w3.org/2000/svg" >
</svg>
这意味着当我缩放该元素时,它内部的实际形状会相应地缩放(到目前为止效果很好).
This means that when I scale that element, the actual shapes inside it scale accordingly (so far so good).
如您所见,我已经设置了 viewBox,使原点位于中心.我想在该元素内绘制一个 x 轴和一个 y 轴,我这样做:
As you can see, I have set up the viewBox so that the origin is in the center. I would like to draw an x- and a y-axis within that element, which I do thus:
<line x1="-1000" x2="1000" y1="0" y2="0" />
同样,这很好用.但是,理想情况下,该轴始终只有 1px 宽.当我缩放父 svg 元素时,我对轴变粗不感兴趣.
Again, this works fine. Ideally, though, this axis would always be only 1px wide. I have no interest in the axes getting fatter when i scale the parent svg element.
那我是不是搞砸了?
推荐答案
您可以使用 vector-effect
属性设置为 non-scaling-stroke
,参见 文档.另一种方法是使用 transform(ref)
.
You can use the vector-effect
property set to non-scaling-stroke
, see the docs. Another way is to use transform(ref)
.
这将适用于支持 SVG Tiny 1.2 中那些部分的浏览器,例如 Opera 10.回退包括编写一个小脚本来执行相同的操作,基本上反转 CTM 并将其应用于不应缩放的元素.
That will work in browsers that support those parts from SVG Tiny 1.2, for example Opera 10. The fallback includes writing a small script to do the same, basically inverting the CTM and applying it on the elements that shouldn't scale.
如果您想要更清晰的线条,您还可以禁用抗锯齿(shape-rendering=optimizeSpeed
或 shape-rendering=crispEdges
) 和/或玩定位.
If you want sharper lines you can also disable antialiasing (shape-rendering=optimizeSpeed
or shape-rendering=crispEdges
) and/or play with the positioning.
这篇关于SVG 中的固定笔画宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!