font-family:
;
Copy and paste me:
function measureText(string, fontSize = 10) { const widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.5,0.6,0.7,1.3,1,1.5,1.2,0.4,0.6,0.6,0.8,1.3,0.5,0.6,0.5,0.6,1,1,1,1,1,1,1,1,1,1,0.5,0.5,1.3,1.3,1.3,0.9,1.6,1.1,1.1,1.1,1.2,1,0.9,1.2,1.2,0.5,0.6,1.1,0.9,1.4,1.2,1.3,1,1.3,1.1,1,1.1,1.2,1.1,1.6,1.1,1.1,1.1,0.6,0.6,0.6,1.3,1,0.8,1,1,0.9,1,1,0.6,1,1,0.4,0.5,1,0.4,1.6,1,1,1,1,0.7,0.8,0.6,1,0.9,1.3,0.9,0.9,0.8,1,0.5,1,1.3] const avg = 0.9536842105263161 return string .split('') .map(c => c.charCodeAt(0) < widths.length ? widths[c.charCodeAt(0)] : avg) .reduce((cur, acc) => acc + cur) * fontSize }
Example usage:
measureText('Hello world', 12) // 106.80000000000001
Hello world
127px
No DOM measurements in this demo
1338px
The quick brown hare trailed the tortoise in the limit
1230px
I am at the office eating a bagel
885px
Toph
164px
Notice the kerning-induced error above
940px
That's my given name to myself by myself, see I see movies
1692px
ASCII only :(
371px
The moré ‘Unicöde’ the worse the åpprøxîmátioñ
1997px