# Measure the exact pixel width of any text
Is your text overflowing its container? Need to know how much space a heading takes up before rendering it? The browser Canvas API allows you to measure the exact width of any text string with pixel precision, without rendering it in the DOM. # Why character counting is not enough
Modern typefaces are proportional: each glyph has a different width. A "W" can take up three times more space than an "i". The number of characters tells you nothing about the actual visual space the text occupies. -
Web design: Prevent overflow in buttons, labels and table cells.
-
SEO: Search engines truncate titles by pixels, not by characters.
-
Canvas and PDF: Calculate the exact position before drawing text programmatically.
-
Tooltips and bubbles: Dynamically size containers based on inner text.
# How measurement works with Canvas
The ctx.measureText() method of the Canvas API returns a TextMetrics object with a width property reflecting the CSS pixel width using the currently active font. This tool configures the context with your font, size, weight and style before measuring.
const ctx = document.createElement('canvas').getContext('2d');
ctx.font = '700 16px Inter, system-ui, sans-serif';
const width = ctx.measureText('Hello World').width; // e.g. 74.5
# Privacy and local processing
All calculation happens in your browser. No text, code snippet or private data leaves your device.
Google Fonts typefaces
To measure a Google Fonts typeface accurately, first make sure it is loaded on the page or installed on your system. Otherwise the browser will fall back to a substitute font and the result will differ.