Explain Codes LogoExplain Codes Logo

Calculate text width with JavaScript

javascript
text-measurement
dom-vs-canvas
performance-optimization
Anton ShumikhinbyAnton Shumikhin·Dec 6, 2024
TLDR

Calculate the pixel width of text in JavaScript by creating a temporary span, assigning it the same font style as your target text, and measuring it with offsetWidth. Here's a simplified function:

function getTextWidth(text, font) { let span = document.createElement('span'); span.style.cssText = `font: ${font}; visibility: hidden; white-space: nowrap;`; // "Do I make you invisible baby, yeah?" — Austin Powers span.textContent = text; document.body.appendChild(span); let width = span.offsetWidth; document.body.removeChild(span); return width; } // Example usage: let width = getTextWidth('The quick brown fox', '16px Arial'); console.log(width); // Prints the width in pixels of your sly text

This function applies the same font style that you're using for your text and measures its width as it would appear on your webpage.

Using DOM: Pros and cons

The getTextWidth function serves countless scenarios by simulating the text's visibility on the page without showing it to the user. This approach proves useful while handling dynamic text resizing scenarios, calculating layout dimensions, and ensuring that data visualization labels fit within boundaries without overlapping.

However, it's crucial to ensure that the temporary span's styling, including padding, margin, and border, simulates the text's intended environment to avoid any miscalculations. Be aware that repeated calls to offsetWidth can cause layout thrashing, which may impact page performance.

Bespoke Measure-tape: HTML5 Canvas

The HTML5 Canvas.measureText method offers better precision and performance than DOM-based methods. Most importantly, the Canvas operations do not impact global state, ensuring you do not inadvertently alter overall page layout. Canvas provides sub-pixel accuracy, perfect for detailed typographic work such as a layout for a complex infographic or a custom word cloud generator.

Embracing the Canvas

Here's how you can compose a utility function to harness the full potential of the measureText method:

function measureTextCanvas(text, font) { let canvas = document.createElement('canvas'); let context = canvas.getContext('2d'); context.font = font; return context.measureText(text).width; } // Example usage: let canvasWidth = measureTextCanvas('I am speed!', '16px Arial'); // Lightning McQueen, is that you? console.log(canvasWidth); // Prints the width of your speedy text

Canvas also provides access to detailed text properties like textAlign, textBaseline, and direction, which helps you align the text perfectly every time.

Caveats of the Canvas

Although HTML5 Canvas is performance-optimized and offers greater accuracy than DOM, it carries some slight overhead: it does need to create a canvas and initialize its context. However, in most use-cases, the performance benefits outweigh the minor setup cost.