JavaScript helper: getTextWidth [TypeScript]

Here’s a quick JavaScript helper snippet to calculate width of a string, based on a supplied font styling.

Written in TypeScript.

Credit goes to https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393

/**
 * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
 *
 * @param {String} text The text to be rendered.
 * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
 *
 * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
private getTextWidth(text: string, font: string): number {
	// re-use canvas object for better performance
	let canvas = document.createElement("canvas");
	let context = canvas.getContext("2d");
	context.font = font;
	let metrics = context.measureText(text);

	return metrics.width;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.