Search code examples
javascripthtmlcanvasbaseline

HTML5 Canvas: Drawing lines along text baselines


The HTML5 Canvas API can draw horizontal line strokes, and it can also align text along various typographic baselines (hanging, alphabetic, ideographic). But can it align line strokes along those same baselines, producing something like this image from the WHATWG spec?


Solution

  • Unfortunately only chrome can help you with this problem at this time as it is the only popular browser that fully supports the TextMetrics object that provides some more information about the size of the current font allowing you to work out the various baselines.

    Use CanvasRenderingContext2D.measureText() to get the TextMetrics object. See MDN TextMetrics for more information.