Getting svg container size in snapSVG?

What is the correct way to get the size of a paper object using SnapSVG once it is created?

My HTML is 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 am observing here is a bounding box that has a "0" for all attributes, so I cannot rely on the bounding box values ​​here. Are there any ways to do this without going to the parent element?

What I essentially want is the width and height of the SVG, so I can draw shapes of the appropriate size for the view.

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

+3
javascript width height
Dec 22 '15 at 20:36
source share
2 answers

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

But an SVG element is like any other DOM element - you can get its width and height in several ways. You can get the object by ID or any other and use .offsetWidth or .offsetHeight.

You can also cross the object itself. I have no idea if this works in all browsers, but if you really want to use a snap object, you can 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 in which it is contained. Why can't you just use element.width () and element.height ()?

+5
Mar 08 '16 at 22:07
source share

I found that getBBox() does not work on paper (Snap drawing surface), only on elements in paper. But node.clientWidth works for me for Snap.svg papers. Demo below.

 var paper = Snap("#mySVG"); paper.rect(0, 0, 200, 100).attr({fill : "#cde"}); //var tMessage0 = paper.getBBox().width; // throws an error var tMessage1 = paper.text(4, 24, "paper width = " + paper.node.clientWidth); var tMessage2 = paper.text(4, 48, "text width = " + tMessage1.getBBox().width); 
 <script src="https://cdn.jsdelivr.net/snap.svg/0.1.0/snap.svg-min.js"></script> <body> <svg id="mySVG" width="200" height="100"> </svg> </body> 
0
Aug 19 '17 at 3:19 on
source share



All Articles