Extended Canvas2D text metrics (github repo)

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 height, ascent, descent, leading and bounding box metrics.

(For some reason this library does the right thing in Opera and Safari, but renders the wrong thing in the main canvas. The "metrics" canvas, however, shows the text for metrics computation rendered quite correctly, so I don't know what's going on ...)

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: