6

Having used Postscript for years, I am now learning SVG. There is a feature of PS that I have not been able to replicate so far: zero-width lines. In PS, a line with zero width is always visible: PostScript converts zero line width to the smallest printable width. On the screen, when zooming they never get any thinkness, yet are visible no matter the scale. I have used them when I wanted to render very thin lines, without worring about the final resolution I was going to use, and they turned out really useful.

However, in the official SVG docs (https://www.w3.org/TR/svg-strokes/) it says that:

A zero value causes no stroke to be painted. A negative value is invalid.

Is there a way in SVG to build zero-width lines in the sense of PostScript?

1
  • 1
    Vector effect non-scaling-stroke perhaps Aug 2, 2018 at 13:20

1 Answer 1

8

As Robert said, the nearest thing to what you want in SVG is vector-effect="non-scaling-stroke". This fixes the stroke width at 1 no matter how the SVG is scaled.

This works on Chrome and Firefox (and probably Opera - haven't checked), but AFAIK not IE/Edge.

<svg viewBox="0 0 100 100">
  <rect x="10" y="10" width="80" height="80"
        fill="none" stroke="black" stroke-width="1"
        vector-effect="non-scaling-stroke"/>
</svg>

Note that antialiasing will come into play depending on the position of the lines. The position will be affected by the scale.

If your lines are rectilinear (horizontal or vertical), you might also want to use shape-rendering="crispEdges". This will turn off antialiasing for the shape on which it is used, resulting in sharp one-pixel lines.

<svg viewBox="0 0 100 100">
  <rect x="10" y="10" width="80" height="80"
        fill="none" stroke="black" stroke-width="1"
        vector-effect="non-scaling-stroke" shape-rendering="crispEdges"/>
</svg>

5
  • @LeBeau thanks, not exactly the same but close enough!
    – zeycus
    Aug 2, 2018 at 16:39
  • Why doesn't this work in Firefox 90 and Chromium 91? Jul 29, 2021 at 9:18
  • @MarkJeronimus Which part is not working for you? I'm using Chrome 92 and FF 90 on Win10, and it's working as expected. Jul 29, 2021 at 13:51
  • 1
    when I zoom the page (even this page when I run the code snippet), the lines change thickness. Aug 4, 2021 at 12:39
  • If you are using the browser zoom, then yest they will change. This feature only applies to SVG internal scale. Aug 5, 2021 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.