demo · v141

Rich TextMetrics

Draw text on a canvas, then ask the enhanced TextMetrics API for per-line and selection rectangles. The orange overlay rectangles below come straight from tm.getSelectionRects() — no manual layout.

probing TextMetrics extensions…

the call

const ctx = canvas.getContext("2d");
ctx.font = "32px serif";
const tm = ctx.measureText(text);
// NEW: select rects for a substring (start, length)
const rects = tm.getSelectionRects(4, 15);
// NEW: actual bounding-box rect for the whole text
const box = tm.getActualBoundingBox();
// NEW: per-glyph cluster results
const clusters = tm.getTextClusters?.();
for (const r of rects) {
  ctx.fillStyle = "rgba(209,26,42,0.25)";
  ctx.fillRect(r.x, r.y, r.width, r.height);
}

see also