Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting font metrics in JavaScript?

I'm currently working on a JavaScript project that uses the HTML5 canvas as a rendering target. In order for my code to play nicely with the (rigidly specified) interfaces I've been provided, I need to be able to take a font and extract the ascent and descent heights of that font. This will allow clients to more accurately position the text. I'm aware that I can change where the text draws by setting the textBaseline attribute, but I actually need the numeric values describing these different heights. Is there a simple way to do this? If not, is there a (hopefully lightweight) library that can handle it for me? Most of the proposed solutions I've found are heavyweight font rendering libraries, which seems like massive overkill for this problem.

like image 539
templatetypedef Avatar asked May 28 '11 23:05

templatetypedef


3 Answers

This article on HTML5 Typographic Metrics discusses the problem and a part solution using CSS - although the integer rounding of offsetTop etc is a problem (potentially can use getBoundingClientRect() to get proper floating point values for some browsers).

like image 60
robocat Avatar answered Nov 07 '22 18:11

robocat


The short answer is that there is no built in way and you are sort-of on your own.

Because of this, most people simply estimate them. Some people pre-calculate all the values, which isn't too much work provided you are using only a few fonts.

The third way is to make a canvas in memory and print some letters (say, a Q and an O) and programatically attempt to determine the ascent and descent using per-pixel collision. It's a pain and can be slow depending on the number of fonts and how accurate you want to be, but it is the most accurate way of going about it if you do not want to pre-compute the values.

like image 41
Simon Sarris Avatar answered Nov 07 '22 19:11

Simon Sarris


Just as a reference here: The width of the text can be measured with:

ctx.measureText(txt).width

http://www.w3schools.com/tags/canvas_measuretext.asp

like image 42
Damocles Avatar answered Nov 07 '22 18:11

Damocles