Created
February 2, 2018 21:30
-
-
Save amsheehan/1ced73a474c226398d717933f8b78811 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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