How to render svg elements with crisp edges while still keeping anti-aliasing?

后端 未结 3 1529
花落未央
花落未央 2020-12-07 15:39

Is there a way to render svg elements with crisp edges while still keeping anti-aliasing?

I\'m creating a browser-based tool that works in modern br

相关标签:
3条回答
  • 2020-12-07 15:58

    If you want your boxes to appear sharp without any blurring due to antialiasing, and without using crispEdges mode, make sure the line edges are on pixel boundaries. So, for example, if your lines are an odd number of pixels wide, give them coordinates that are at 0.5 of a pixel.

    <rect x="10.5" y="10.5" width="150" height="20" 
        stroke-width="1px" fill="none" stroke="black"/>
    

    And on the boundary if the stroke width is even.

    <rect x="10" y="10" width="150" height="20" 
        stroke-width="2px" fill="none" stroke="black"/>
    

    Of course, this only really works if your SVG is being rendered at 1:1. That is, it's not being rescaled by the browser. And only for lines that are horizontal and vertical.

    0 讨论(0)
  • 2020-12-07 16:08

    Perhaps you set shape-rendering property for root svg element.
    You should set shape-rendering property for each shape elements, like this.

    <?xml version="1.0" standalone="no"?>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <rect x="10" y="10" width="150" height="20" shape-rendering="crispEdges" 
            fill="none" stroke="black"/>
        <path d="M80,30l100,100" shape-rendering="optimizeQuality" 
            stroke="black" stroke-width="5"/>
    </svg>
    
    0 讨论(0)
  • 2020-12-07 16:17

    [I'm posting this as an answer rather than a comment, because I want to post a picture. Otherwise, this is a comment on the useful post by @defghi1977 . +1 to him, by the way.]

    <?xml version="1.0" standalone="no"?>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <rect x="10" y="10" width="150" height="20" shape-rendering="crispEdges" 
              fill="none" stroke="black" />
        <rect x="10" y="50" width="150" height="20" shape-rendering="auto" 
              fill="none" stroke="black" />
        <path d="M40,30l100,100" shape-rendering="crispEdges" 
              stroke="black" stroke-width="5" />
        <path d="M80,30l100,100" shape-rendering="auto" 
              stroke="black" stroke-width="5" />
    </svg>
    

    Produced

    enter image description here

    This was rendered by Firefox 38.0.5 .
    In Internet Explorer 11, both shape-rendering setting produces the same result with anti-aliasing and not crisp.

    0 讨论(0)
提交回复
热议问题