Pixels needed to render a string

How to get the number of pixels that a rendered string will occupy

topic : jQuery
first published: July 2013

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.
getPixelDims(control.scratch,'11111111111')
Object {width: 44, height: 10}
getPixelDims(control.scratch,'...........')
Object {width: 22, height: 10}
getPixelDims(control.scratch,'XXXXXXXXXXX')
Object {width: 55, height: 10}


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. 
var scratch = $(document.createElement('span'))
.addClass('shadow')
.css('display','none')
.css("font-size",control.options.labelFontSize + "px");
  • 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
function getPixelDims(scratch,t) {
// scratch is an elemen with the correct styling, t is the text to be counted in pixels
scratch.empty();
scratch.append(document.createTextNode(t));
return { width: scratch.outerWidth(), height: scratch.outerHeight() } ;
}
  • Call it like this
var dim = getPixelDims(scratch, text);
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 here. Today's snippet is here.

For help and more information join our forum,follow the blog or follow me on twitter .




Comments