fontmetrics.js

A JavaScript library that extends the Canvas2D context.measureText(<String>) with additional typographical metrics

Stars
56

This library updates the canvas2d ctx.measureText() function so that it returns not just a string's width, but also its height, ascent wrt the baseline, descent wrt the baseline, the leading distance (the number of pixels between the baselines of two consecutive lines of text, pronounced like the metal "lead", not like the management "leader"), as well as the string's bounding box.

Simply include on a page as:

and measureText will return a much more complete object, structured as follows:

{ fontsize: , /* as set on the canvas/context / width: , / typesetting width of the text / height: , / typesetting height of the text / ascent: , / height above the baseline for this text / descent: , / depth below the baseline for this text / leading: , / the 'lead' (metal) spacing between the baselines of two lines / bounds: / the bounding box for the rasterised text on a canvas / { minx: , / can be negative / miny: , / can be negative / maxx: , / not necessarily the same as width / maxy: / not necessarily the same as height */ } }

Note: all numbers represent screen pixels (not typographical points)

See http://pomax.github.com/fontmetrics.js/ for a demonstration.

This library is covered by an MIT (Expat flavour) license.

Related Projects