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; }