← Chrome 160 reference · All APIs
v160 · graphics · enabled by default
Enhanced Canvas TextMetrics
Adds first-class Canvas 2D text shaping, selection geometry, caret hit-testing, and per-run/per-cluster glyph rendering via shapeText(), ShapedText, GlyphRun, and fillGlyphRun(s) / strokeGlyphRun(s) on both CanvasRenderingContext2D and OffscreenCanvasRenderingContext2D. Although the feature retains its historical “Enhanced Canvas TextMetrics” name from the Chrome 144–149 Origin Trial, Chrome 160 ships the redesigned shaping architecture aligned with WebKit’s CanvasTextShaping model, leaving TextMetrics itself unchanged and exposing per-run metrics via GlyphRun.textMetrics().
at a glance
| Shipped in | Chrome 160 (desktop, Android, Android WebView), enabled by default — listed under “Enabled by default” in the milestone=160 listing and confirmed in the ChromeStatus API record |
|---|---|
| Runtime flag & OT history | Blink runtime feature ExtendedTextMetrics (in runtime_enabled_features.json5; Origin Trial ran Chrome 144–149 under the earlier TextMetrics/TextCluster design before the Chrome 160 ShapedText/GlyphRun redesign) |
| Spec & explainers | WHATWG HTML PR #11000 · whatwg/html#10677 · WebKit CanvasTextShaping explainer (#137) · Igalia text-metrics-additions explainer |
| Intent | blink-dev Intent to Ship (prior: Intent to Experiment) |
| TAG review | w3ctag/design-reviews#1095 (Issues open) |
| Tracking bug | issues.chromium.org/341213359 |
| Web platform tests | element/text 2d.text.shape.* · offscreen/text 2d.text.shape.* |
| ChromeStatus | 5075532483657728 — Enhanced Canvas TextMetrics |
why it exists
ctx.measureText() only returns aggregate metrics for an entire string. Canvas-rendered editors, design tools, and frameworks (such as Flutter Web’s WebParagraph) previously had to approximate caret positions, selection highlight rectangles, and per-character animations by calling measureText() on substrings — which breaks ligatures, kerning, complex shaping, and bidirectional runs — or by synchronizing hidden DOM elements. Separating shaping into ctx.shapeText(text) creates an immutable ShapedText snapshot whose runs, grapheme clusters, bounding boxes, selection rectangles, and caret offsets can be queried accurately and rendered individually via fillGlyphRun(s) and strokeGlyphRun(s).
Design evolution note: Early Origin Trial builds (Chrome 144–149) added getSelectionRects(), getTextClusters(), and fillTextCluster() directly on TextMetrics/TextCluster. Following Origin Trial feedback and WebKit’s CanvasTextShaping explainer, Chromium redesigned the shipped Chrome 160 surface around shapeText(), ShapedText, and GlyphRun so TextMetrics remains untouched and future multi-style FormattedText overloads can layer cleanly on top. Legacy TextCluster declarations still present under Blink’s ExtendedTextMetrics flag during cleanup are not part of the Chrome 160 shipping contract.
Syntax
The Chrome 160 shaping surface adds five methods to the 2D rendering context (shared by CanvasRenderingContext2D and OffscreenCanvasRenderingContext2D) and introduces two new interfaces, ShapedText and GlyphRun:
partial interface mixin CanvasText {
ShapedText shapeText(DOMString text);
undefined fillGlyphRun(GlyphRun glyphRun, double x, double y);
undefined strokeGlyphRun(GlyphRun glyphRun, double x, double y);
undefined fillGlyphRuns(sequence<GlyphRun> glyphRuns, double x, double y);
undefined strokeGlyphRuns(sequence<GlyphRun> glyphRuns, double x, double y);
};
[Exposed=(Window,Worker)]
interface ShapedText {
readonly attribute double width;
sequence<GlyphRun> glyphRuns();
sequence<GlyphRun> glyphClusters();
sequence<GlyphRun> glyphClusters([EnforceRange] unsigned long start, [EnforceRange] unsigned long end);
sequence<DOMRectReadOnly> selectionRects([EnforceRange] unsigned long start, [EnforceRange] unsigned long end);
DOMRectReadOnly actualBoundingBox([EnforceRange] unsigned long start, [EnforceRange] unsigned long end);
unsigned long advanceToPosition(double advance);
double positionToAdvance([EnforceRange] unsigned long position);
};
[Exposed=(Window,Worker)]
interface GlyphRun {
readonly attribute unsigned long start;
readonly attribute unsigned long end;
readonly attribute double x;
readonly attribute double y;
readonly attribute double width;
TextMetrics textMetrics();
};
All character offsets and ranges (start, end, position, and advanceToPosition() results) are 0-based UTF-16 code units, matching JavaScript String indexing, DOM Range/Selection, and Intl.Segmenter. Detailed contracts follow for shapeText(), ShapedText width, glyphRuns(), and glyphClusters(), selectionRects(), actualBoundingBox(), advanceToPosition(), and positionToAdvance(), GlyphRun, and fillGlyphRun(s) / strokeGlyphRun(s).
base_rendering_context_2d.idl; Blink shaped_text.idl; Blink glyph_run.idl.
ctx.shapeText(text)
Inputs. Accepts a single DOMString text (coerced per standard WebIDL string conversion). No optional arguments or max-width parameter are defined in Chrome 160.
Outputs. Resolves the canvas element’s style/layout tree (when attached to a document with a frame), snapshots the context’s current font, resolved writing direction (ltr or rtl), textAlign, and textBaseline, shapes the string into visual runs via Blink’s PlainTextPainter, and returns a new immutable ShapedText object. If called on an HTMLCanvasElement belonging to a frame-less document (for example created via document.implementation.createHTMLDocument()), Blink returns an empty ShapedText whose width is 0 and whose glyphRuns() / glyphClusters() are empty arrays.
base_rendering_context_2d.cc (BaseRenderingContext2D::shapeText); Blink shaped_text.cc.
ShapedText.width, glyphRuns(), and glyphClusters()
Inputs.
st.width: read-onlydoubleattribute representing the total advance width of the shaped string.st.glyphRuns(): takes no parameters.st.glyphClusters(): takes either no arguments (full string) or two[EnforceRange] unsigned longUTF-16 code unit indices(start, end)representing the half-open slice[start, end).
Outputs.
glyphRuns()returns asequence<GlyphRun>in visual left-to-right order. Adjacent clusters sharing the same resolved font and bidi direction are merged into a singleGlyphRun; mixed-script font fallbacks (such as emoji or Hebrew/Arabic mixed with Latin) or bidi level changes split into separate runs.glyphClusters()returns minimal renderable grapheme clusters asGlyphRuninstances so callers can style, transform, or animate individual characters/ligatures while preserving shaping context. CallingglyphClusters()with no arguments on an empty string returns[]; passing(start, end)returns every cluster whose[cluster.start, cluster.end)range intersects[start, end).- Each returned
GlyphRunhasxalready shifted by the snapshottedtextAlignoffset (for example, negativexwhentextAlignis"center"or"right") andyset to0relative to the draw origin.
shaped_text.cc (glyphRuns, glyphClusters); WPT 2d.text.shape.glyph-clusters-position.tentative.html; WPT 2d.text.shape.fillGlyphRuns-and-strokeGlyphRuns.tentative.html.
selectionRects(), actualBoundingBox(), advanceToPosition(), and positionToAdvance()
| Method | Inputs | Output & coordinate semantics |
|---|---|---|
selectionRects(start, end) | Two [EnforceRange] unsigned long UTF-16 indices defining [start, end) | Returns sequence<DOMRectReadOnly> covering the selected highlight region(s) relative to the text alignment anchor and snapshotted baseline. Multiple disjoint rects may be returned for bidirectional text. Returns [] when start >= end (within bounds). |
actualBoundingBox(start, end) | Two [EnforceRange] unsigned long UTF-16 indices defining [start, end) | Returns a single tight DOMRectReadOnly union of glyph ink bounds for the slice, offset by (-textAlignDx, baselineY) to match the draw origin. |
advanceToPosition(advance) | double advance (horizontal offset from the alignment anchor; may be negative when aligned center/right) | Returns the nearest 0-based UTF-16 caret index (unsigned long) via hit-testing. Values beyond the left/right edges clamp to 0 / width; mixed-bidi boundaries apply Blink’s CorrectForMixedBidi() adjustment. |
positionToAdvance(position) | [EnforceRange] unsigned long position in [0, text.length] | Returns a double horizontal caret advance offset relative to the alignment anchor (for LTR with textAlign = "left": 0 at index 0, up to st.width at text.length). |
shaped_text.cc; WPT 2d.text.shape.position-to-advance.tentative.html; WPT 2d.text.shape.advance-to-position-edge-cases.tentative.html.
GlyphRun interface
Inputs & construction. GlyphRun has no public constructor; instances are produced exclusively by ShapedText.glyphRuns() and ShapedText.glyphClusters() and retain an internal reference to their originating ShapedText and resolved font face.
Outputs & members.
start/end(readonly unsigned long): inclusive start and exclusive end UTF-16 code unit indices into the original string passed toshapeText().x/y(readonly double): shaped position offset of this run relative to the anchor point passed tofillGlyphRun()/strokeGlyphRun()(incorporating the snapshottedtextAlign).width(readonly double): advance width of this run/cluster.textMetrics(): returns aTextMetricsobject describing the exact ascent, descent, bounding box, and advance metrics for thisGlyphRun’s slice and resolved font. Blink lazily constructs and caches theTextMetricsinstance on first call.
glyph_run.idl; Blink glyph_run.cc; WPT 2d.text.shape.glyph-clusters-position.tentative.html.
fillGlyphRun(), strokeGlyphRun(), fillGlyphRuns(), and strokeGlyphRuns()
Inputs. Each method takes either a single GlyphRun (fillGlyphRun / strokeGlyphRun) or a sequence<GlyphRun> (fillGlyphRuns / strokeGlyphRuns) followed by destination anchor coordinates double x and double y.
Outputs & style precedence. Each run renders at (glyphRun.x + x, glyphRun.y + y) using the font, direction, textAlign, and textBaseline snapshotted when shapeText() ran — mutating those four properties on the context afterwards does not shift or re-shape previously created GlyphRuns. By contrast, active paint and compositing state (fillStyle, strokeStyle, lineWidth, shadow*, globalAlpha, transforms, and clipping regions) is applied at draw time, enabling per-cluster color gradients, transforms, and animations. fillGlyphRuns(runs, x, y) and strokeGlyphRuns(runs, x, y) iterate through runs in order and draw each run at the shared anchor (x, y).
base_rendering_context_2d.cc (lines 2132–2195); WPT 2d.text.shape.fillGlyphRun-range.tentative.html; WPT 2d.text.shape.fillGlyphRuns-and-strokeGlyphRuns.tentative.html.
Errors, bounds rules, and edge cases
| Condition | Affected methods | Behavior |
|---|---|---|
Negative index or value outside unsigned long | glyphClusters(start, end), selectionRects(start, end), actualBoundingBox(start, end), positionToAdvance(position) | Throws WebIDL TypeError via [EnforceRange] unsigned long conversion. |
start >= text.length or end > text.length | actualBoundingBox(start, end), glyphClusters(start, end) | Throws DOMException (IndexSizeError). Note Blink’s CheckRange() rejects start === text.length here (tracked in Blink source comment for crbug 580852205). |
start > text.length or end > text.length | selectionRects(start, end) | Throws DOMException (IndexSizeError); accepts start === text.length and returns [] when start >= end. |
position > text.length | positionToAdvance(position) | Throws DOMException (IndexSizeError). |
Out-of-bounds advance | advanceToPosition(advance) | Does not throw; clamps to the visual start/end of the string and returns a valid UTF-16 index. |
Non-finite x or y (NaN, Infinity) | fillGlyphRun(), strokeGlyphRun(), fillGlyphRuns(), strokeGlyphRuns() | WebIDL double (non-unrestricted) throws TypeError on non-finite coordinates before entering Blink’s draw path. |
shapeText("") (empty string) | shapeText(), glyphRuns(), glyphClusters(), GlyphRun.textMetrics() | Succeeds with width === 0, glyphRuns() and no-arg glyphClusters() return []; passing (0, 0) to actualBoundingBox() or 2-arg glyphClusters() throws IndexSizeError because 0 >= 0. |
Feature detection: Test "shapeText" in CanvasRenderingContext2D.prototype (or "shapeText" in OffscreenCanvasRenderingContext2D.prototype inside workers) before invoking shapeText() or rendering GlyphRun objects.
shaped_text.cc; WPT actualBoundingBox-exceptions; WPT selection-rects-exceptions; WPT glyph-clusters-exceptions.
Context, exposure, and lifecycle
Exposure & prerequisites. ShapedText, GlyphRun, shapeText(), fillGlyphRun(), strokeGlyphRun(), fillGlyphRuns(), and strokeGlyphRuns() are exposed in both Window and Worker (via OffscreenCanvasRenderingContext2D). No secure context, permission, or user activation is required. When using web fonts loaded via @font-face / FontFaceSet, await document.fonts.ready before calling shapeText() so shaping runs against the loaded typeface rather than a fallback font.
Lifecycle & immutability. A ShapedText instance is an immutable snapshot of the string and the context’s font, direction, textAlign, and textBaseline at the time shapeText() was called. GlyphRun objects retain a GC-traced reference to their parent ShapedText and resolved font data, and cache their textMetrics() result on first access. Re-shape whenever the string, font size/family, alignment, baseline, or writing direction changes; reuse the same ShapedText and GlyphRun arrays across animation frames when only colors, shadows, or transforms change.
shaped_text.idl; Blink glyph_run.cc; WPT offscreen 2d.text.shape.*.
Examples
No Chrome Platform Showcase demo exists yet for Chrome 160 enhanced-canvas-textmetrics (checked 2026-11-24).
Selection highlights, tight ink bounds, and pointer hit-testing with shapeText()
if ("shapeText" in CanvasRenderingContext2D.prototype) {
const ctx = canvas.getContext("2d");
ctx.font = "28px system-ui, sans-serif";
ctx.textAlign = "left";
ctx.textBaseline = "alphabetic";
const originX = 24;
const originY = 72;
const text = "Hello 👋 עולם";
const shaped = ctx.shapeText(text);
// 1. Draw selection highlight rectangles for UTF-16 range [0, 8)
ctx.fillStyle = "rgba(11, 87, 208, 0.25)";
for (const rect of shaped.selectionRects(0, 8)) {
ctx.fillRect(originX + rect.x, originY + rect.y, rect.width, rect.height);
}
// 2. Outline tight ink bounding box for the full shaped text
const ink = shaped.actualBoundingBox(0, text.length);
ctx.strokeStyle = "#b3261e";
ctx.strokeRect(originX + ink.x, originY + ink.y, ink.width, ink.height);
// 3. Render shaped text runs
ctx.fillStyle = "#111";
ctx.fillGlyphRuns(shaped.glyphRuns(), originX, originY);
// 4. Convert a pointer X coordinate to a UTF-16 caret index and back
canvas.addEventListener("pointerdown", (e) => {
const localX = e.offsetX - originX;
const caretIndex = shaped.advanceToPosition(localX);
const caretAdvance = shaped.positionToAdvance(caretIndex);
console.log({ caretIndex, caretAdvance, totalWidth: shaped.width });
});
}
Source: WPT 2d.text.shape.position-to-advance.tentative.html; WPT 2d.text.shape.fillGlyphRuns-and-strokeGlyphRuns.tentative.html.
Per-cluster styling, animation, and GlyphRun.textMetrics() inspection
const ctx = canvas.getContext("2d");
ctx.font = "600 40px Georgia, serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const shaped = ctx.shapeText("Wave");
const clusters = shaped.glyphClusters(); // sequence<GlyphRun>
// Mutating ctx.font / ctx.textAlign after shapeText() does NOT alter these GlyphRuns.
const palette = ["#0b57d0", "#b3261e", "#146c2e", "#8f4e00"];
clusters.forEach((run, i) => {
const metrics = run.textMetrics();
const dy = Math.sin(i * 0.9) * 10;
// Draw each cluster with its own fillStyle and strokeStyle while preserving kerning.
ctx.fillStyle = palette[i % palette.length];
ctx.strokeStyle = "#111";
ctx.lineWidth = 1.5;
ctx.fillGlyphRun(run, canvas.width / 2, canvas.height / 2 + dy);
ctx.strokeGlyphRun(run, canvas.width / 2, canvas.height / 2 + dy);
console.log({
range: [run.start, run.end],
pos: [run.x, run.y],
width: run.width,
ascent: metrics.actualBoundingBoxAscent,
});
});
// Batch-draw a subset of clusters via strokeGlyphRuns()
ctx.strokeGlyphRuns(shaped.glyphClusters(1, 3), canvas.width / 2, canvas.height / 2 + 48);
Source: WPT 2d.text.shape.glyph-clusters-position.tentative.html; WPT 2d.text.shape.fillGlyphRun-range.tentative.html.
Browser compatibility
| Browser | shapeText() / ShapedText / GlyphRun | Evidence / notes | Base TextMetrics (BCD) |
|---|---|---|---|
| Chrome (desktop, Android, WebView) | 160 | Enabled by default in Chrome 160 across desktop, Android, and WebView per ChromeStatus API record (prior Origin Trial in 144–149 used earlier TextMetrics/TextCluster methods) | 1 |
| Edge | 160 (mirror) | Chromium-based; mirrors Chromium’s ExtendedTextMetrics implementation | 12 (mirror) |
| Firefox | No release | Mozilla standards-positions#1144 (No signal yet) | 3.5 |
| Safari | No release | WebKit standards-positions#436 (Neutral; Chrome 160’s shapeText() / ShapedText / GlyphRun redesign aligns with WebKit/explainers#137) | 4 |
api/TextMetrics.json; mozilla/standards-positions#1144; WebKit/standards-positions#436.
Security and privacy
Canvas 2D font metrics and rendered glyphs are already a well-known browser fingerprinting surface because installed system fonts and shaping engines vary across devices. ChromeStatus notes that shapeText(), ShapedText, GlyphRun, and fillGlyphRun(s) / strokeGlyphRun(s) expose finer-grained geometry of text already measurable via measureText() and drawable via fillText(), introducing no novel cross-origin leak, permission boundary change, or storage channel. Security and privacy reviews are listed as Pending in the ChromeStatus API record (checked 2026-11-24).
Specifications
| Specification / proposal | Status & scope |
|---|---|
| WHATWG HTML PR #11000 — Extend Canvas TextMetrics for editing and text styling | Open PR (being aligned with shapeText() / ShapedText / GlyphRun per ChromeStatus) |
| WHATWG HTML issue #10677 | Design discussion on text shaping vs TextMetrics extensions |
| WebKit CanvasTextShaping explainer (PR #137) | Core shaping architecture (shapeText(), ShapedText, GlyphRun) |