News

Measuring Text in HTML5

For a while now, I’ve been doing quite a bit of work in HTML5/Javascript/CreateJS.  While the work is enjoyable, dealing with getting the bounds of a text field seems to have many solutions.

I’ve read through just about every one I could find (and believe me when I say –  there are many), looked through examples and did many tests.  After all that, I’m sharing my final solution for getting the bounds for a string:

Example call:

Fiddle: https://jsfiddle.net/neoRiley/qcphL0g4/

I give some credit to schickling on stackoverflow (only 6 votes?!) for the main inspiration as he aptly identified what I think is the key component: document.createTextNode()

I’d been using JQuery and wanted a solution that worked without a 3rd party tool.  The only thing that reliably gave me the same bounds as JQuery is the above method.  I’ve added debug support should you want to verify that it is indeed testing your string correctly.

GetBoundsOfText

Have a bandit day!