Jul 3rd 2013How to determine the width and height of SVG-text before rendering with Raphaël

For a current project I needed to determine the size of SVG-text before it was displayed. There is a really simple quick-and-dirty solution to this:

function renderedTextSize(string, font, fontSize) {
  var paper = Raphael(0, 0, 0, 0);
  paper.canvas.style.visibility = 'hidden';

  var el = paper.text(0, 0, string);
  el.attr('font-family', font);
  el.attr('font-size', fontSize);

  var bBox = el.getBBox();
  paper.remove();

  return {
    width: bBox.width,
    height: bBox.height
  };
}

What's happening in this code, is: we're creating an invisible SVG-element and rendering some text on it with any given font and text-size. Then we get the text element's bounding box to retrieve the string's rendered width and height.

The library I'm using here is called Raphaël and has become pretty standard for SVG-stuff on the web. Check it out!