.getComputedTextLength() returns different values in IE and Chrome
Asked Answered
F

1

16

I've encountered a problem, when I wrote some small program. There is an SVG textNode:

textMeasureNode.style.cssText 
"font-family: "Open Sans", Arial, Helvetica, sans-serif; font-size: 22px; font-style: oblique; font-weight: normal; fill: #333333;" 
and 
textMeasureNode.textContent 
"Q1"

When I call the function:

textMeasureNode.getComputedTextLength() 

I get different values in IE and Chrome.

IE:

49.269996643066406

Chrome:

29.34765625

It seems, that font-style: oblique affects these results. Has anyone encountered this problem?

Faust answered 4/2, 2015 at 2:57 Comment(0)
H
1

I've done some testing with this in Chrome, Safari, and Firefox, and each renders with a slightly different length. You are definitely seeing some unexpected behaviour. It's not specific to Open Sans or it being oblique (different styles will change the length differently in different browsers). Even the inclusion of fallback fonts significantly changed the length in Chrome (but not FireFox or Safari). My best guess is this is due to how each browser chooses to render fonts in SVGs, so it would be best not to make anything dependent on specific lengths.

In the SVG specification, getComputedTextLength() is defined as:

The total sum of all of the advance values from rendering all of the characters within this element, including the advance value on the glyphs (horizontal or vertical), the effect of properties ‘kerning’, ‘letter-spacing’ and ‘word-spacing’ and adjustments due to attributes ‘dx’ and ‘dy’ on ‘tspan’ elements.

So there are quite a few variable things that can affect the length, and if you try a fairly long sentence (so lots of glyphs, spaces, etc) the differences are more pronounced. Not ideal behaviour to have it vary between browsers, but probably reasonable given all the constraints of building a web browser.

Hellenic answered 26/1, 2022 at 21:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.