5

I want to read:

  • width,height,x,y measurements

for a particular SVG element.


I suppose that easiest way to go about this is to fetch the minimum bounding box first and read it's properties.

How can I access this?

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167

4 Answers4

8

If you have a reference to the DOM node, use

svgNode.getBoundingClientRect()

https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect

Edit: SVG Edit has a method to return currently selected elements:

svgCanvas.getSelectedElems()

so in the above example:

svgNode = svgCanvas.getSelectedElems()[0];
svgNode.getBoundingClientRect();
pawel
  • 35,827
  • 7
  • 56
  • 53
  • thats what i use exactly. However i want to get the bounding box of a selected element. An element that has been selected on the canvas. I select the element then click a button that fires a function that gets its bounding box. I dont know what to substitute in the place of "svgNode" to get the value of a Selected element. – nicholaswmin Feb 18 '13 at 13:09
  • Oh, thanks for the clarification. I've edited my answer accordingly. – pawel Feb 18 '13 at 13:37
4

Please see http://granite.sru.edu/~ddailey/svg/BBox0M.svg for the example and answer.

In brief, this code works for me in Chrome:

<script>
function foo(evt)
{
    console.log(evt.target.getBBox());      
}
</script>

<svg>
    <circle onclick="foo(evt)" r="20%" cx="50%" cy="50%"/>
</svg>
MSC
  • 3,286
  • 5
  • 29
  • 47
2

Assuming you have a handle to the element, I would think that this would work, no?

box = svgedit.utilities.getBBox(selected);
Bellave Jayaram
  • 366
  • 1
  • 2
  • 11
  • @niteshsingh My question is tagged with `svg-edit`, an online SVG editor hence this answer makes use of one of svg-edit's utility libraries. – nicholaswmin Nov 01 '18 at 04:32
0

I'm not sure if I'm understanding you correctly, but if you're looking to get the height or width of a jQuery element, use width() and height():

log("The svg is " + $("img").width() + "px wide.");
log("The svg is " + $("img").height() + "px tall.");

JSFiddle example: http://jsfiddle.net/gGWU4/

turiyag
  • 2,757
  • 2
  • 22
  • 21
  • Actually i want to get the bounding box of an svg element that is clicked. The bounding box is a tightfitting box sourrounding the corners of any given svg element. – nicholaswmin Feb 17 '13 at 21:29
  • Would you be looking for code like this? http://files.myopera.com/MacDev_ed/svg/coords/showbbox.js From this page: http://files.myopera.com/MacDev_ed/svg/coords/sandbox.svg – turiyag Feb 17 '13 at 21:37
  • This tells the height and the width, not the bounding box. – Paul Rooney Mar 28 '18 at 04:05