Created
June 9, 2021 02:34
-
-
Save aminnj/5ca372aa2def72fb017b531c894afdca to your computer and use it in GitHub Desktop.
arial character widths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var d1 = document.createElement("div"); | |
d1.id = "test3"; | |
d1.innerHTML = "test"; | |
d1.style = "width: fit-content; padding: 0px; margin: 0px; font-family: Arial, sans-serif;"; | |
document.documentElement.appendChild(d1); | |
var d2 = document.createElement("div"); | |
d2.id = "test3"; | |
document.documentElement.appendChild(d2); | |
d2.innerHTML = ""; | |
var N = 100; | |
for (var i = 32; i < 127; i++) { | |
var s = String.fromCharCode(i).replace(" "," "); | |
d1.innerHTML = s.repeat(N); | |
var width = d1.getBoundingClientRect().width; | |
d2.innerHTML += `"${s}": ${width/N},<br>`; | |
} | |
Nice little script! I made some changes to generalize it for my needs:
- Wraps functionality as a function
- Accepts two parameters: a list of strings (characters) to test, and extra styles
- Returns a map of input strings to width in pt
- Converts width from px to pt
- Adds
font-size
property to hint that you can run the test for any font size - Eliminates output div
- Deletes test div once all the measurements are complete
function characterPtWidths(characters, extraStyles) {
var div = document.createElement("div");
div.style = "width: fit-content; padding: 0px; margin: 0px; font-family: Arial, sans-serif; font-size: 10pt; " + (extraStyles || "");
document.documentElement.appendChild(div);
var N = 100;
var result = {}
for (var c of characters) {
var s = c.replace(" "," ");
div.innerHTML = s.repeat(N);
var width = div.getBoundingClientRect().width;
result[s] = width / N * 4 / 3.0
}
document.documentElement.removeChild(div);
return result;
}
Example usage:
// numbers and "."
console.log("pt widths for selected characters:", characterPtWidths([".","0", "1", "2","3","4","5","6","7","8","9"]))
// numbers and "." at font-size: 15pt
console.log("pt widths for selected characters:", characterPtWidths([".","0", "1", "2","3","4","5","6","7","8","9"], "font-size: 15pt;"))
// all ascii characters like the original
console.log("pt widths for selected characters:", characterPtWidths(Array.from((new Array(127)).keys().filter(i => i >= 32).map(x => String.fromCharCode(x)))))
Awesome, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dummy div filled with repeated characters to measure their individual widths. For Arial, relative widths of ascii characters are