mitchgrasso
mitchgrasso

Reputation: 125

SVG - scaling issues with images

Scaling a parent DIV containing an SVG that has image over a colored rect shows hairline edges from the underlying rect.

<div style='transform: scale(0.79454)'>
    <svg width="1280" height="720">
      <rect fill="yellow" width="1280" height="720"/>
      <image width="1280" height="720" transform='matrix(1.4,0,0,1.4,-200,-150)' xlink:href="https://storage.googleapis.com/firebase-beautifulslides.appspot.com/test/dawid-zawila-279995.jpg"/>
    </svg>
</div>

In the screenshot below, there is a yellow box beneath the image. Both are the same size but you can see the yellow box "bleed" out from the edges a bit (you may to view the full image or the fiddle below to see it clearly).

enter image description here This artifact happens whether or not I transform the image node and also appears when I try scaling the SVG using a viewBox instead of the parent div. It's somewhat better in Safari than in Chrome but it does still happen in certain cases.

Here's a fiddle https://jsfiddle.net/e17ea4j5/

Is there any fix to this?

Upvotes: 1

Views: 1018

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101820

What you seeing is the result of anti-aliasing. The semi-transparent pixels at the edges of the yellow rectangle are visible through the semi-transparent pixels at the edges of the image.

There isn't really any elegant solution to eliminate those issues. Especially when when you are scaling by fractions (eg. 1.4 and 0.79454).

You are left with somewhat hacky solutions like putting a black stroke around your rectangle.

<rect fill="yellow" width="1280" height="720" stroke="black" stroke-width="1"/>

body{
      background: black;
      margin: 0;
    }
<body>
  <div style='transform: scale(0.79454)'>
    <svg width="1280" height="720">
      <rect fill="yellow" width="1280" height="720" stroke="black" stroke-width="1"/>
      <image width="1280" height="720" transform='matrix(1.4,0,0,1.4,-200,-150)' xlink:href="https://storage.googleapis.com/firebase-beautifulslides.appspot.com/test/dawid-zawila-279995.jpg"/>
    </svg>
  </div>
</body>

Upvotes: 2

Related Questions