Skip to content

Instantly share code, notes, and snippets.

@piecioshka
Last active March 11, 2019 11:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piecioshka/cce6ea53ba0db1a4700e to your computer and use it in GitHub Desktop.
Save piecioshka/cce6ea53ba0db1a4700e to your computer and use it in GitHub Desktop.
[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