Skip to content

Instantly share code, notes, and snippets.

@06b
Created November 25, 2018 03:46
Show Gist options
  • Save 06b/06b8b6eec892dc05ae633ee2c918d707 to your computer and use it in GitHub Desktop.
Save 06b/06b8b6eec892dc05ae633ee2c918d707 to your computer and use it in GitHub Desktop.
Call this function and pass in the name of the font you want to check for availability. - https://www.kirupa.com/html5/detect_whether_font_is_installed.htm
//
// Call this function and pass in the name of the font you want to check for availability. - https://www.kirupa.com/html5/detect_whether_font_is_installed.htm
//
function doesFontExist(fontName) {
// creating our in-memory Canvas element where the magic happens
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
// the text whose final pixel size I want to measure
var text = "abcdefghijklmnopqrstuvwxyz0123456789";
// specifying the baseline font
context.font = "72px monospace";
// checking the size of the baseline text
var baselineSize = context.measureText(text).width;
// specifying the font whose existence we want to check
context.font = "72px '" + fontName + "', monospace";
// checking the size of the font we want to check
var newSize = context.measureText(text).width;
// removing the Canvas element we created
delete canvas;
//
// If the size of the two text instances is the same, the font does not exist because it is being rendered
// using the default sans-serif font
//
if (newSize == baselineSize) {
return false;
} else {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment