Getting screen boundingboxes in svg
Thursday, 12. March 2009, 21:32:27
Last time we explored how to get boundingboxes of any svg element. Today I'd like to expand this a bit, and to show what the client (or screen) boundingbox can be used for.
How to get the screen boundingbox
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 getScreenBBoxAsRectElement(elm)
{
var bb = elm.getScreenBBox();
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;
}
As you see from last time, it only changed one tiny thing: getBBox became getScreenBBox. However, not all browsers have native support for the getScreenBBox method so we have to provide a scriptbased fallback solution. This additional scriptfile can be dynamically loaded by another script if the native method is found to be missing.
Here's an example of how to show the boundingbox as a border around any element in an svg, along with the values in text format. The boundingbox in userspace is shown with a red border, the screen boundingbox is shown with blue border.
The script that shows the boundingboxes and their dimensions can be viewed here. To use it in another svg file just download that script and the getScreenBBox fallback script to the same directory, and add a 'script' element to the svg file you want to use it in, like this:
... <script xlink:href="showbboxdims.js"/> ...Tested and works in Opera 9+, Firefox 3, Safari 4.









