Skip to content

Instantly share code, notes, and snippets.

@Temzasse
Created March 31, 2025 10:43
Show Gist options
  • Save Temzasse/b3cc947f9ffe0143ff826f0e78770fb2 to your computer and use it in GitHub Desktop.
Save Temzasse/b3cc947f9ffe0143ff826f0e78770fb2 to your computer and use it in GitHub Desktop.
Get text width
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