Skip to content

Instantly share code, notes, and snippets.

@aminnj
Created June 9, 2021 02:34
Show Gist options
  • Save aminnj/5ca372aa2def72fb017b531c894afdca to your computer and use it in GitHub Desktop.
Save aminnj/5ca372aa2def72fb017b531c894afdca to your computer and use it in GitHub Desktop.
arial character widths
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(" ","&nbsp;");
d1.innerHTML = s.repeat(N);
var width = d1.getBoundingClientRect().width;
d2.innerHTML += `"${s}": ${width/N},<br>`;
}
@joetabers
Copy link

joetabers commented Oct 28, 2024

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(" ","&nbsp;");
    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)))))

@aminnj
Copy link
Author

aminnj commented Oct 30, 2024

Awesome, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment