1. Use the canvas' measureText() method
const measureWidth = function (text, font) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = font;
const metrics = context.measureText(text);
return metrics.width;
};
2. Use a fake element
const measureWidth = function (text, font) {
const ele = document.createElement('div');
ele.style.position = 'absolute';
ele.style.visibility = 'hidden';
ele.style.whiteSpace = 'nowrap';
ele.style.left = '-9999px';
ele.style.font = font;
ele.innerText = text;
document.body.appendChild(ele);
const width = window.getComputedStyle(ele).width;
document.body.removeChild(ele);
return width;
};
See also