Extended Canvas2D text metrics

This page demonstrates the fontmetrics.js library, which updates the canvas2d ctx.measureText(string) function so that it returns not just a string's width, but also its ascent, descent, leading and bounding box metrics.

Canvas "cvs" (200×200):
What it should look like:
a jpeg of what the canvas should look like when rendered by the browser
JavaScript:
var canvas = document.getElementById('cvs'),
    context = canvas.getContext("2d");

var w=200, h=200, testtext="this is a string";
canvas.style.font = "30px Times";
context.font = "30px Times";
var metrics = context.measureText(testtext);
var xstart = (w - metrics.width)/2;
context.fontFamily = "Times";
context.fillStyle = "#99BBFF";
context.fillRect(xstart, h/2-metrics.ascent,
                 metrics.bounds.maxx-metrics.bounds.minx,
                 1+metrics.bounds.maxy-metrics.bounds.miny);
context.fillStyle = "grey";
context.fillText(testtext, xstart, h/2);

Metrics object:



    

Canvas state used in fontmetrics.js for metrics computation: