Getting SVG container size in snapSVG?

为君一笑 提交于 2019-12-04 14:42:26

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()?

I find that getBBox() doesn't work on a paper (a Snap "drawing surface"), only on elements in a 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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!