Max SchmittMS
3rd July 2013

How 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) = 'hidden'
var el = paper.text(0, 0, string)
el.attr('font-family', font)
el.attr('font-size', fontSize)
var bBox = el.getBBox()
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!

Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.