Search code examples
svgscaling

How to make SVG scaling correctly?


I have an SVG like this :

<svg 
    xmlns="http://www.w3.org/2000/svg" 
    id="demo" 
    style="bottom:0px;left:0px;right:0px;top:0px;margin:auto;position:absolute;" 
    viewBox="0 0 40 28">
    <rect x="0" y="0" width="40" height="14" fill="blue"/>
    <rect x="0" y="14" width="40" height="14" fill="green"/>
</svg>

I would expect whatever its size, it will contains only pure blue or pure green.

However, that's not the case :

result

The same with zoom on it :

result zoomed

As you can see, there this half-transparent white border between blue and green rectangle.

Where does it come from ? Can I avoid it ?

Thank you.


Solution

  • You can turn off antialiasing if you want via shapeRendering:crispEdges. You might not like the result if you apply it to things that do not consist solely of vertical or horizontal lines though.

    The viewBox also forces the shape to maintain an aspect ratio which can cause the edges to be blank to maintain that aspect ratio. Again you can turn that off via preserveAspectRatio="none" but your shape will then distort to match the container aspect ratio.

    <svg 
        xmlns="http://www.w3.org/2000/svg" 
        id="demo" 
        style="bottom:0px;left:0px;right:0px;top:0px;margin:auto;position:absolute;shape-rendering:crispEdges" 
        viewBox="0 0 40 28" preserveAspectRatio="none">
        <rect x="0" y="0" width="40" height="14" fill="blue"/>
        <rect x="0" y="14" width="40" height="14" fill="green"/>
    </svg>