Created
March 31, 2025 10:43
-
-
Save Temzasse/b3cc947f9ffe0143ff826f0e78770fb2 to your computer and use it in GitHub Desktop.
Get text width
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
export function getTextWidth(text: string, element: HTMLElement): number { | |
const canvas = document.createElement('canvas'); | |
const context = canvas.getContext('2d'); | |
if (!context) return 0; | |
const fontWeight = getCssStyle(element, 'font-weight') || 'normal'; | |
const fontSize = getCssStyle(element, 'font-size') || '14px'; | |
const fontFamily = getCssStyle(element, 'font-family') || 'Times New Roman'; | |
const font = `${fontWeight} ${fontSize} ${fontFamily}`; | |
context.font = font; | |
const metrics = context.measureText(text); | |
canvas.remove(); | |
return metrics.width; | |
} | |
function getCssStyle(element: HTMLElement, prop: string) { | |
return window.getComputedStyle(element, null).getPropertyValue(prop); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment