Skip to content

Instantly share code, notes, and snippets.

@jrweth
Created October 21, 2016 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrweth/bd652c062acf7836c811351e03f3892b to your computer and use it in GitHub Desktop.
Save jrweth/bd652c062acf7836c811351e03f3892b to your computer and use it in GitHub Desktop.
Function to calculate the font-size to fit a given number of characters into a given pixel width.
/**
* Gets the font size needed to cram a given number of Characters into a setWidth
*
* This function works by actually inserting some pixels into the page and then
* measuring the resulting element
*
* @param numChars int Number of characters you want to fit
* @param setWidthPx int Number of pixels you want the characters to fit into
* @param options {
* tagName string the tag name to place the characters in for measuring (default "div")
* fontFamily string the font-family to measure (will use container default)
* className string the class name to add to the element for measuring
* parentEl DomNode he element to insert the element into for measuring (default document.body)
* textToMeasure string the string to use to measure the font width
* (default "AbcdEfghiJklmnOpqrsTuvwXyz 0. 1, 2' 3$ 4! 5@ 6( 7) 8; 9:")
*
* }
* @author J. Reuben Wetherbee <jrweth@gmail.com>
*/
function getFontSizeForCharsInSetWidth(numChars, setWidthPx, options)
{
//check input variables
if(typeof setWidthPx == 'undefined') setWidthPx = screen.width;
if(typeof options == 'undefined') options = {};
//set options if not set
var fontPixelSize;
var tagName = ("tagName" in options) ? options.tagName : 'div';
var parentEl = ("parentEl" in options) ? options.parentEl : document.body;
var measurementText = ("measurementText" in options)
? options.measurementText
: "AbcdEfghiJklmnOpqrsTuvwXyz 0. 1, 2' 3$ 4! 5@ 6( 7) 8; 9:";
//create our element to insert into dom for measuring
var el = document.createElement(tagName);
//handle the options if set
if("className" in options) el.className = options.className;
if("fontFamily" in options) el.style.fontFamily = options.fontFamily;
//set up some style attributes for our element for proper measurement
el.style.position = 'absolute';
el.style.height = 'auto';
el.style.width = 'auto';
el.style.whiteSpace = "nowrap";
el.style.visibility = "hidden";
el.style.fontSize = "10px";
//add the text for measurement
el.innerHTML = measurementText;
//add the child
parentEl.appendChild(el);
//get the px size of the font
fontPixelSize = setWidthPx * 10 * el.innerHTML.length / ((el.clientWidth+1) * numChars);
parentEl.removeChild(el);
return fontPixelSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment