在snapSVG中获取SVG容器大小? [英] Getting SVG container size in snapSVG?

查看:315
本文介绍了在snapSVG中获取SVG容器大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用SnapSVG获取'paper'对象的大小的正确方法是什么?一旦创建它?

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

我的HTML看起来如下:

My HTML looks something as follows:

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

然后是Javascript代码:

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

我在这里看到的是所有属性的边界框都有'0',所以我不能依赖这里的边界框值。有没有办法做到这一点,而不必转到父元素?

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?

我基本上想要的形式所有这些是SVG的宽度和高度,所以我可以为视图绘制适当大小的形状。

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小提琴,说明问题: https://jsfiddle.net/ajmas/kdnx2eyf/1/

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

推荐答案

画布上的getBBox()返回包含该画布上所有元素的边界框。由于你的SVG中没有元素,它会返回全0。

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.

但是SVG元素就像任何其他DOM元素一样 - 你可以得到它的宽度和高度不同方式的数量。您可以通过ID或其他方式检索对象,并使用.offsetWidth或.offsetHeight。

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.

您也可以遍历对象本身。我不知道这是否适用于所有浏览器,但如果你真的想使用snap对象,你可以这样做:

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

但你也是只需使用它包含的div设置它的高度和宽度。为什么不能只使用element.width()和element.height()?

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

这篇关于在snapSVG中获取SVG容器大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆