There are ways to measure text in the browser, taking into account the font size. However, you could get a performance improvement if you only measure the different characters, and then you combine the characters into words. For example, measure the letters
o, and then use the measurements to compute the measurement of
foo. The problem is,
foo is not equal to
f + o + o (in the browser), as seen here:
var c = document.createElement('canvas') var s = c.getContext('2d') c.font = '400 normal 12px Arial' var a = s.measureText('f').width var b = s.measureText('o').width var x = a + b + b var y = s.measureText('foo').width console.log(x) //=> 14.0662841796875 console.log(y) //=> 14.143630981445312
f + o + o = 14.07 foo = 14.14
foo is slightly longer than
f + o + o. I am wondering if there is any way to figure this out in advance. That is, for a given font, if there is a way to know, when letters are combined, what the final size will be, without just measuring the whole string of text as one chunk.
I think this is because of ligatures or kerning which I am not too familiar with. But maybe there is a way to get a list of all the ligatures/kernings for a particular font, which will tell you the ratio of "compression" or "space" it removes or adds to letters in certain combinations.
Wondering if anything like this exists, or if it is at all possible. Not exactly sure I am pinpointing the problem (i.e. that it is related to kerning/ligatures), but assuming it is the problem, wondering how to get a list of the ligatures/kerning for a font, so I can do the measurements in advance. Maybe it is somehow encoded in the font eot or ttf or related files, or maybe there is a list on some website. If it's not the problem, then wondering what the problem is and how one might get the data to solve it.