ed.blog

You will be vectorized.

Getting screen boundingboxes in svg

, , ,

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. View live example.

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.

How to get the boundingbox of an svg elementHow to get the svg elements intersected by a given rectangle

Comments

Spadar ShutSpShut Tuesday, December 29, 2009 10:47:20 PM

Can i get the dimensions of the whole svg image with this script when the svg element doesn't have width, height and viewBox attributes?

Erik DahlströmMacDev_ed Tuesday, January 12, 2010 3:01:33 PM

If the svg has no width,height and no viewBox then you can get an approximation by calling getBBox on the root svg element, and then using the result as the new viewBox. It won't always work great (part of stroke can still be outside, filters and markers are not taken into account), but most svg's do have either of width+height or viewBox.

Write a comment

New comments have been disabled for this post.