Why would you need to ? Perhaps for layout, you may want to place text where it will fit, or change the font size if it doesn’t. On example I came across was using when SVG in d3 concept browser, I needed to position a node at the end of some text, but in such a way that all text for all nodes started at the same position – as below

Notice how the text all starts at the same x co-ordinate. This was achieved by correctly positioning the nodes based on how much space their associated text would take when rendered.
This can be trickier than you would think. You need to take account of styling, classes, selected font and since font is proportional even the content of the text is relevant. Look at the results below – 3 strings, same length of string, 3 different widths.

Here’s how…

  • Create a scratch element (or many if you have multiple stylings), and apply the styling characteristics of the element that the text will finally be rendered in. You can do this in html, or dynamically as in the extract below. Set its display attribute to ‘none’ since you won’t actually be showing it. 
  • Use this function to do a ‘trial- rendering’ in this scratch element, it will return the width and height in pixels of the text you want to display
  • Call it like this

You can then access dim.width and dim.height for the space the text would occupy if rendered.

That’s it.

There are various snippets throughout this site. Some of them have been categorized and some not. I’ll use the page for my ‘snippet of the day’ and change them when I remember. You can find other assorted snippets here and hereToday’s snippet is here.