How to get the size of the SVG container?

5,545 views
Skip to first unread message

André-John Mas

unread,
Dec 22, 2015, 4:09:36 PM12/22/15
to Snapsvg
Hi,

Can anyone tell me the correct way to get the size of the SVG container?

I have the following HTML

<div id="myContainer" style="width: 900px; height: 100px" />


and the following Javascript:

function initViewer(elementId) {
 
var element, elementRef, snap;
  elementRef
= '#' + elementId;
  element
= $(elementRef);
  element
.append('<svg style="width: ' + element.width() + 'px; height: ' + element.height() + 'px; border: solid 1px black;"/>');
  snap
= Snap(elementRef + ' svg');
  console
.log(snap.getBBox());
}

initViewer
('myContainer')

The border on the SVG shows that it is being rendered at the dimensions asked for (verified in Chrome and Safari on MacOS X), but getBBox() returns '0' for all its attributes. I can't seem to see a reliable way to get the container's dimensions? I would the dimensions, so I can draw using the appropriate bounding dimensions.

Any suggestions?

Andre

André-John Mas

unread,
Dec 27, 2015, 2:24:43 PM12/27/15
to Snapsvg
Given the lack of response and not finding anything conclusive in the docs or on the web, I am going to assume that this is not possible. For now I am using JQuery to get the dimension of the parent container and then just using that.

André-John Mas

unread,
Dec 31, 2015, 1:32:27 PM12/31/15
to Snapsvg
Some more experimentation and it would seem the Snap API would need to be enhanced to support this. In the meantime 'element.clientWidth' seems to be the most reliable approach, since the 'snap.getBBox()' always returns 0 for it entries. The JS Fiddle representing some of my experimentation:

https://jsfiddle.net/ajmas/k2h96c2w/

Note, a few gotchas:
  - non-css width & height element attributes on the svg node don't seem very reliable. Best use the CSS approach
  - if you have a div, make sure it is not self-closing, since this screws with the selector. Good: <div></div> , bad: <div/>



samk...@gmail.com

unread,
Dec 31, 2015, 8:49:07 PM12/31/15
to Snapsvg
I was trying to do something like this as well. If you want the width and height of the SVG element how it is shown on the page you need to use clientHeight and clientWidth. getBBox() returns the size of the bounding box of all sub-elements of the SVG element. If you have elements inside the SVG element that are larger than the size of the SVG box, getBBox() returns the bounding box of those.

Reply all
Reply to author
Forward
0 new messages