Proposals/getBBoxOf

From SVG

This is a proposal for ISSUE-2283.

It is common to want to get the bounding box of an element in a different element's coordinate space. This can be computed in script, but it is tedious. For example with the following document:

<g id="A" transform="...">
  <g transform="...">
    <path id="P" d="..."/>
  </g>
</g>

Say you want to click on the <path> and create a <rect> as a child of g#A that shows the bounding box of the <path>. You need to:

  • do bbox = P.getBBox()
  • Construct SVGPoint objects for each of the four corners of bbox
  • do m = P.getTransformToElement(A)
  • Transform each of the four SVGPoints with m
  • Compute the bounding box of these four points (a bunch of Math.min() and Math.max() calls)
  • Create the <rect> and set its x/y/width/height based on this computed bbox

A few approaches to simplify this have been discussed, and the one we seemed to settle on was to introduce a new method that can return the bounding box of another element in the current element's coordinate space.

Proposal: Extend the SVGLocatable interface with a getBBoxOf method:

interface SVGLocatable {
   ...
   SVGRect getBBoxOf(SVGLocatable element);
};

which does the following:

  1. Let this be the SVGLocatable element on which the method was called.
  2. Let r1 be the result of calling element.getBBox().
  3. Let p1, p2, p3 and p4 be the four points of r1 (in any order).
  4. Let p5, p6, p7 and p8 be the four points p1, p2, p3 and p4 transformed from the coordinate space of this to the coordinate space of element.
  5. Let r2 be a new SVGRect object that is the tight bounding box in the coordinate space of element that contains p5, p6, p7 and p8.
  6. Return r2.