Home > Software engineering >  Difference in length calculation for SVG text element
Difference in length calculation for SVG text element

Time:03-03

I am creating an SVG using the svg crate. To properly place a border around a <text> element, I calculate the length of the text beforehand using the rusttype crate.

However, my browser (Safari) seems to render the text with a different length.

The simplified version of my SVG is here:

<svg viewBox="0 0 210 297" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M105,20 L304,20 L304,77 L105,77 z" fill="none" stroke="black" stroke-width="1"/>
<text font-family="Arial" font-size="12" x="110" y="57">My extremely very, very, very, long Goal</text>
</g>
</svg>

I do calculate the length as found suggested Rendered without textLength

Rendered SVG with calculated textLength attribute: Rendered with calculated textLength

CodePudding user response:

There are several possible reasons for the discrepancies between measing text in two different libraries/engines.

  • Kerning differences
  • Ligature handling differences
  • On-screen font renderers often adjust glyph position to better align with screen pixels. Especially for small font sizes.
  • There are other potential font-specific features and variations that may be affecting rendering

Most likely is probably #3. Try setting font size to something big (eg. 100) to see if this is the case. You could also try experimenting with the CSS text-rendering property.

  • Related