demo · v141
Selection Rects
A canvas-based text input that paints a real selection highlight using getSelectionRects(start, end). Drag your cursor across the canvas — every selection rectangle the platform would render is returned as an array of DOMRectReadOnly, ready to fill underneath the glyphs.
drag to select. shift-click to extend.
the call
const metrics = ctx.measureText(text);
const rects = metrics.getSelectionRects(start, end); // DOMRectReadOnly[]
ctx.fillStyle = "rgba(0, 34, 255, 0.25)";
for (const r of rects) {
ctx.fillRect(originX + r.x, originY + r.y, r.width, r.height);
}
ctx.fillStyle = "#000";
ctx.fillText(text, originX, originY);
why this angle
Pre-141, canvas-based editors (Figma-style design surfaces, code editors like Monaco's experimental canvas renderer, slide builders) had to recompute selection geometry by measuring substrings and stacking the widths. That fails for shaped scripts where glyphs combine, for bidi runs where character indices don't follow visual order, and for any font with negative letter-spacing or kerning. getSelectionRects returns exactly what the platform itself would render — the layout engine doing the hard work.