Skip to content

Instantly share code, notes, and snippets.

@piecioshka piecioshka/getTextWidth.js
Last active Mar 11, 2019

Embed
What would you like to do?
[get text long in pxs] Uses canvas.measureText to compute and return the width of the given text of given font in pixels #Canvas
/**
* 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 http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
function getTextWidth(text, font) {
// if given, use cached canvas for better performance
// else, create new canvas
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.