Last active
March 11, 2019 11:10
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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