files/en-us/web/api/textmetrics/index.md
{{APIRef("Canvas API")}}{{AvailableInWorkers}}
The TextMetrics interface represents the dimensions of a piece of text in the canvas; a TextMetrics instance can be retrieved using the {{domxref("CanvasRenderingContext2D.measureText()")}} method.
This example demonstrates the baselines the TextMetrics object holds. The default baseline is the alphabeticBaseline. See also the {{domxref("CanvasRenderingContext2D.textBaseline")}} property.
<canvas id="canvas" width="550" height="500"></canvas>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const baselinesAboveAlphabetic = [
"fontBoundingBoxAscent",
"actualBoundingBoxAscent",
"emHeightAscent",
"hangingBaseline",
];
const baselinesBelowAlphabetic = [
"ideographicBaseline",
"emHeightDescent",
"actualBoundingBoxDescent",
"fontBoundingBoxDescent",
];
const baselines = [...baselinesAboveAlphabetic, ...baselinesBelowAlphabetic];
ctx.font = "25px serif";
ctx.strokeStyle = "red";
baselines.forEach((baseline, index) => {
const text = `Abcdefghijklmnop (${baseline})`;
const textMetrics = ctx.measureText(text);
const y = 50 + index * 50;
ctx.beginPath();
ctx.fillText(text, 0, y);
const baselineMetricValue = textMetrics[baseline];
if (baselineMetricValue === undefined) {
return;
}
const lineY = baselinesBelowAlphabetic.includes(baseline)
? y + Math.abs(baselineMetricValue)
: y - Math.abs(baselineMetricValue);
ctx.moveTo(0, lineY);
ctx.lineTo(550, lineY);
ctx.stroke();
});
{{EmbedLiveSample('Baselines_illustrated', 700, 550)}}
When measuring the x-direction of a piece of text, the sum of actualBoundingBoxLeft and actualBoundingBoxRight can be wider than the width of the inline box (width), due to slanted/italic fonts where characters overhang their advance width.
It can therefore be useful to use the sum of actualBoundingBoxLeft and actualBoundingBoxRight as a more accurate way to get the absolute text width:
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const text = "Abcdefghijklmnop";
ctx.font = "italic 50px serif";
const textMetrics = ctx.measureText(text);
console.log(textMetrics.width);
// 459.8833312988281
console.log(
textMetrics.actualBoundingBoxRight + textMetrics.actualBoundingBoxLeft,
);
// 462.8833333333333
{{Specifications}}
{{Compat}}