How to get the boundingbox of an svg element
Wednesday, January 21, 2009 8:00:00 AM
A common scenario is that you have an svg file (which often has a 'viewBox' attribute) created in a graphics editor like Inkscape, and now want to make this static svg file interactive or animated. Another scenario is that you want to place/layout elements dynamically and need to know the positions and size of some given elements.
Prerequisites
First it's important to at least be somewhat acquainted with the various coordinate systems at play inside an svg file.
- The initial viewport (sometimes referred to as the client- or screen-) coordinate system
- This is the actual coordinate system that you see on your computer screen, often defined in pixels. You will need to use this when handling mouseevents for example, since they are going to be in this coordinate system, and they may need to be converted into userspace.
- The userspace coordinate system
- This is the coordinate system at the place of any given element in the svg file. It depends on what transforms have been specified as well as what the viewport coordinate system specified by the parent
svgelement(s) and the'viewBox'if any.
The fun stuff
In order to get the geometric boundingbox of an svg element you can call the getBBox DOM method. This method returns a rectangle DOM object that corresponds to the boundingbox of the element in user units. The returned DOM object is called an SVGRect, and has the following four properties that can be accessed: x, y, width and height.
Note: The boundingbox object is a snapshot of the element's boundingbox at the time the getBBox method was called. Changing the values of the boundingbox has no effect on the visual appearance of the element.
Here's a simple function that returns the boundingbox of an element as a 'rect' element. If the 'rect' element is inserted just after the element that we got a boundingbox for it would in most cases cover that element.
var svgns = "http://www.w3.org/2000/svg";
function getBBoxAsRectElement(elm)
{
var bb = elm.getBBox();
var rect = document.createElementNS(svgns, "rect");
rect.x.baseVal.value = bb.x;
rect.y.baseVal.value = bb.y;
rect.width.baseVal.value = bb.width;
rect.height.baseVal.value = bb.height;
return rect;
}
Here's an example of how to show the boundingbox as a border around any element in an svg. View live example.
The script that shows the boundingbox as a red rect can be viewed here. To use it in another svg file just download that script and add a 'script' element to the svg file you want to use it in, like this:
... <script xlink:href="showbbox.js"/> ...Tested and works in Opera 9+, Firefox 3 and Safari 3.









Anonymous # Friday, March 12, 2010 11:02:27 AM
Anonymous # Monday, February 21, 2011 1:38:20 PM
Anonymous # Friday, March 11, 2011 11:06:26 AM
Anonymous # Monday, May 9, 2011 6:03:16 PM