Getting SVG container size in snapSVG?

Andre M picture Andre M · Dec 22, 2015 · Viewed 7.8k times · Source

What is the correct way to get the size of the 'paper' object with SnapSVG, as soon as it has been created?

My HTML looks something as follows:

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

And then the Javascript code:

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());
}

What I observe here is the bounding box has '0' for all attributes, so I can't rely on the bounding box values here. Are there any ways of doing this, without have to go to a parent element?

What I am essentially wanting form all this is the width and the height of the SVG, so I can draw the shapes of the appropriate size for the view.

JS Fiddle, illustrating the issue: https://jsfiddle.net/ajmas/kdnx2eyf/1/

Answer

AustinC picture AustinC · Mar 8, 2016

getBBox() on a canvas returns the bounding box that contains all elements on that canvas. Since there are no elements in your SVG, it returns all 0s.

But the SVG element is just like any other DOM element - you could get its width and height in a number of different ways. You could retrieve the object by ID or whatever and use .offsetWidth or .offsetHeight.

You could also traverse the object itself. I have no idea if this works on all browsers but if you really want to use the snap object, you could do this:

snap=Snap(elementRef + ' svg');
snap.node.clientHeight
snap.node.clientWidth

But you also just set the height and width of it using the div it is contained in. Why can't you just use element.width() and element.height()?