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 including this grammarly review app to make sure it is well written.
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:
function getBounds(p_text, p_options, p_debug) { var element = document.createElement('div'), bounds = {width: 0, height: 0}; element.appendChild(document.createTextNode(p_text)); p_options.fontFamily = p_options.fontFamily || "arial"; p_options.fontSize = p_options.fontSize || "12px"; p_options.fontWeight = p_options.fontWeight || "normal"; element.style.fontFamily = p_options.fontFamily; element.style.fontWeight = p_options.fontWeight; element.style.fontSize = p_options.fontSize; element.style.position = 'absolute'; element.style.visibility = p_debug ? 'visible' : 'hidden'; element.style.left = p_debug ? "0px" : "-1000px"; element.style.top = p_debug ? "0px" : "-1000px"; element.style.width = 'auto'; element.style.height = 'auto'; if( p_debug ){ element.style.background = "#FFFF00"; element.style.color = "#000000"; } document.body.appendChild(element); bounds.width = element.offsetWidth; bounds.height = element.offsetHeight; if( !p_debug ) document.body.removeChild(element); return bounds; }
Example call:
function runTest(){ var str = "What size am I?"; var size_0 = getBounds(str, {fontFamily: "arial", fontSize:"14px"}, false); var size_1 = getBounds(str, {fontFamily: "arial", fontSize:"63%"}, true); console.log("perSize: " + size_0.width + ", " + size_0.height); console.log("perSize: " + size_1.width + ", " + size_1.height); }
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.
Have a bandit day!
Tweet