Yulia Z
Yulia Z

Reputation: 11

SVG foreignObject is different when used as an image with src attribute

I have an SVG with some text in a foreignObject that I want to convert to an HTML image element <img src="data:image/svg+xml;utf8,%3Csvg%20xmlns..."> but resulting image looks a little bit different from the SVG. It looks like there is more line height in the resulting image. I've tried with text with different font families but the image and SVG still do not match.

Link to the code - https://jsfiddle.net/2x91gzjo/

JS:

const svgString = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="160"
  height="143">
  <foreignObject width="100%" height="100%"
    style="line-height: normal; letter-spacing:0.25px; font-style:normal; font-weight:normal; color:#000000; font-size:11pt; text-decoration:none; text-align:left;font-kerning:auto;overflow-wrap:break-word;padding:10px;width:160px;height:143px;">
    <style>
      p {
        margin-top: 0px;
        margin-bottom: 0px;
      }
    </style>
    <div xmlns="http://www.w3.org/1999/xhtml" style="">
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
    </div>
  </foreignObject>
</svg>`
document.getElementById('svg').innerHTML = svgString;

const data = 'data:image/svg+xml;utf8,' + encodeURIComponent(svgString);

const img = document.createElement('img');
img.src = data;

document.getElementById('svg').appendChild(img);

CSS:

svg p {
  color: red;
}

svg, img {
  position: absolute;
  left: 10px
}

HTML:

<div id="svg"></div>

On the image below you can see that SVG (colored in red for convenience) has smaller line height than the generated image (colored in black).

Image on top of SVG

It looks like this problem exists only in Chrome MacOS. If you open the jsfiddle link in Firefox the image and the SVG are aligned.

Related questions: SVG with foreignObject has a different height when used as an image src attribute https://bugs.chromium.org/p/chromium/issues/detail?id=1442475 However, not sure how zoom:1/window.devicePixelRatio would help here.

Any workaround is appreciated!

Upvotes: 1

Views: 69

Answers (0)

Related Questions