Created
September 7, 2011 19:51
-
-
Save preslavrachev/1201539 to your computer and use it in GitHub Desktop.
Getting the Bounding Box of an SVG Element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var bb = null; | |
function drawRect(e) | |
{ | |
var elm = e.target; | |
// fixes for 'use' elements | |
if(!elm.getBBox) | |
{ | |
if(elm.correspondingUseElement) | |
elm = elm.correspondingUseElement; | |
} | |
var r = elm.getBBox(); | |
console.log(elm.getBBox) | |
// don't care about the root element | |
var root = document.documentElement; | |
if(root == e.target) { | |
return false; | |
} | |
// remove any old bbox | |
if(bb) { | |
bb.parentNode.removeChild(bb); | |
bb = null; | |
} | |
// make new bbox | |
if(!bb) | |
{ | |
bb = document.createElementNS("http://www.w3.org/2000/svg", "rect"); | |
bb.setAttributeNS(null, "fill", "none"); | |
bb.setAttributeNS(null, "stroke", "red"); | |
bb.setAttributeNS(null, "pointer-events", "none"); | |
root.appendChild(bb); | |
} | |
// outset the rect a bit | |
bb.x.baseVal.value = r.x - 2; | |
bb.y.baseVal.value = r.y - 2; | |
bb.width.baseVal.value = r.width + 4; | |
bb.height.baseVal.value = r.height + 4; | |
// make the bbox rect element have the same user units even though it's the last child of the root element | |
bb.transform.baseVal.clear(); | |
var tfm2elm = elm.getTransformToElement(bb); | |
bb.transform.baseVal.appendItem(bb.transform.baseVal.createSVGTransformFromMatrix(tfm2elm)); | |
} | |
// install listener | |
document.documentElement.addEventListener("mousemove", drawRect, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment