EN
JavaScript - measure text width
3
points
In this article, we would like to show you how to measure text width using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const canvas = document.createElement('canvas'); // helper object in memory
const context = canvas.getContext('2d'); // helper object in memory
context.font = `normal 12px Arial`;
const metrics = context.measureText('Hello World!');
console.log(`text width: ${metrics.width}px`); // text width: 65.1328125px
Solution explaination
Canvas context object provides simple API to measure font metrics. It is necessary just to set specific font-family, font-size, font-weight and use measureText() method that returns metrics for indicated text (metrics like e.g. width).
Reusable function
In this section, you can find simple tool that helps to measure text width using canvas object.
// ONLINE-RUNNER:browser;
const canvas = document.createElement('canvas'); // helper object in memory
const context = canvas.getContext('2d'); // helper object in memory
const createMeasurer = (fontFamily = 'Arial', fontSize = '12px', fontWeight = 'normal') => {
context.font = `${fontWeight} ${fontSize} ${fontFamily}`;
return (text) => {
const metrics = context.measureText(text);
return metrics.width;
};
};
// Usage example:
// font-family: Arial
// font-size: 30px
// font-weight: normal
const measureWidth = createMeasurer('Arial', '30px', 'normal');
const measuredWidth = measureWidth('Hello World!');
console.log(`text width: ${measuredWidth}px`); // text width: 162.83203125px
Hack solution
In this section, you can find solution that mounts invisible element with some text to measure text width. This solution is hack, but it works.
// ONLINE-RUNNER:browser;
const createMeasurer = (fontFamily = 'Arial', fontSize = '12px', fontWeight = 'normal') => {
const element = document.createElement('span');
element.style.padding = '0'; // we don't want to measure paddings if globally used
element.style.position = 'absolute'; // we don't want to impact on other body elements
element.style.right = '150%'; // we want to place element outside body area
element.style.bottom = '150%'; // we want to place element outside body area
element.style.visibility = 'hidden'; // we want to render invisible element
element.style.whiteSpace = 'nowrap'; // we want to render text without automatic break lines
element.style.fontFamily = fontWeight;
element.style.fontSize = fontSize;
element.style.fontWeight = fontWeight;
return (text) => {
element.textContent = text;
document.body.appendChild(element);
const width = element.offsetWidth;
document.body.removeChild(element);
return width;
};
};
// Usage example:
// font-family: Arial
// font-size: 30px
// font-weight: normal
const measureWidth = createMeasurer('Arial', '30px', 'normal');
const measuredWidth = measureWidth('Hello World!');
console.log(`text width: ${measuredWidth}px`); // text width: 158px
Note: this approach requires
<body>element to be mount.