Skip to content

Instantly share code, notes, and snippets.

@amsheehan
Created February 2, 2018 21:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amsheehan/1ced73a474c226398d717933f8b78811 to your computer and use it in GitHub Desktop.
Save amsheehan/1ced73a474c226398d717933f8b78811 to your computer and use it in GitHub Desktop.
// Create rendering context
let ctx = document.createElement('canvas').getContext('2d');
// Get font family, font size, and letter spacing,
const fontFamily = window.getComputedStyle(<HTML ELEMENT>).getPropertyValue('font-family').split(',')[0];
const fontSize = window.getComputedStyle(<HTML ELEMENT>).getPropertyValue('font-size');
const letterSpacing = parseFloat(window.getComputedStyle(<HTML ELEMENT>).getPropertyValue('letter-spacing'));
// Get padding
const paddingLeft = parseInt(window.getComputedStyle(<HTML ELEMENT>).getPropertyValue('padding-left'), 10);
const paddingRight = parseInt(window.getComputedStyle(<HTML ELEMENT>).getPropertyValue('padding-right'), 10);
const fullPadding = paddingLeft + paddingRight;
// Add the font to the rendering context
ctx.font = `${fontSize} ${fontFamily}`;
// Get width of the font
const {width} = ctx.measureText(<TEXT>);
// Get added whitespace from letter spacing
const addedSpace = letterSpacing * <TEXT>.length;
// Add it all up and take the ceiling for whatever you get and that's the width of your shit.
const textWidth = Math.ceil(width + addedSpace + fullPadding);
// I think that should get you what you need. You'd assign this as the width in an inline style.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment