In HTML 5, you can just use the Canvas.measureText method (further explanation here).
Try this fiddle:
If you want to use the font-size of some specific element
myEl, you can make use of the
getCanvasFont utility function:
const fontSize = getTextWidth(text, getCanvasFont(myEl)); // do something with fontSize here...
getCanvasFontSize function takes some element’s (by default: the
body‘s) font and converts it into a format compatible with the Context.font property. Of course any element must first be added to the DOM before usage, else it gives you bogus values.
There are several advantages to this approach, including:
- More concise and safer than the other (DOM-based) methods because it does not change global state, such as your DOM.
- Further customization is possible by modifying more canvas text properties, such as
NOTE: When you add the text to your DOM, remember to also take account of padding, margin and border.
NOTE 2: On some browsers, this method yields sub-pixel accuracy (result is a floating point number), on others it does not (result is only an int). You might want to run
Math.ceil) on the result, to avoid inconsistencies. Since the DOM-based method is never sub-pixel accurate, this method has even higher precision than the other methods here.
According to this jsperf (thanks to the contributors in comments), the Canvas method and the DOM-based method are about equally fast, if caching is added to the DOM-based method and you are not using Firefox. In Firefox, for some reason, this Canvas method is much much faster than the DOM-based method (as of September 2014).
This fiddle compares this Canvas method to a variation of Bob Monteverde’s DOM-based method, so you can analyze and compare accuracy of the results.