Question

Given a SVG graphic something like..

<svg>
  <g id="outer" transform="...">
    <g id="middle" transform="...">
      <g id="inner" transform="...">
        <rect id="anchor" ... />
      </g>
    </g>
  </g>
</svg>

I know I can get the bounding box of #anchor in the coordinate system of #inner using getBBox().

But, how can I get the bounding box of #anchor in the coordinate system of, say, #outer ?

Perhaps using a library like Raphaël or snap.svg (tried myself but failed..).

Was it helpful?

Solution

If you are using just translations it's no problem by using getCTM() of the target.

try:

    <svg id="mySVG" width="400" height="400" >
      <g id="outer" transform="translate(30,40)" onmouseover=outerBB(evt) >
        <g id="middle" transform="translate(130,40)">
          <g id="inner" transform="translate(30,140)" >
          <rect id="anchor" x="10" y="10" width="100" height="100" fill=red />
          </g>
        </g>
      </g>
      <rect id=bbRect pointer-events="none" fill=none stroke='blue' stroke-width="3" />
    </svg>


    function outerBB(evt)
    {
        var target=evt.target
        var bb=target.getBBox()
        var bbx=bb.x
        var bby=bb.y
        var bbw=bb.width
        var bbh=bb.height
        var sctm=target.getCTM()
        var pnt=mySVG.createSVGPoint()
        pnt.x=bbx
        pnt.y=bby
        var PNT = pnt.matrixTransform(sctm);
        bbRect.setAttribute("x",PNT.x)
        bbRect.setAttribute("y",PNT.y)
        bbRect.setAttribute("width",bbw)
        bbRect.setAttribute("height",bbh)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top