Get bounding box for SVG path using jQuery

﹥>﹥吖頭↗ 提交于 2019-11-29 03:45:29

getBBox is a native SVG method and isn't part of jquery so you would need to write

$("#"+ path id)[0].getBBox()

example

If you're getting a non-zero value for the example and a zero value in your code then there must be something else going on that you've not shown us.

The most likely causes are that the path is a child of <defs> i.e. you're only using it indirectly in a pattern or clipPath or alternatively the it has a display style of none in which case it wouldn't be rendered so would have no bounding box.

The getBBox() native implementation in Webkit is buggy, you can find the bug tracker here. Actually It's fixed now

A solution is to use an SVG library that has it's own algorithms for calculating such matters, one of them is Raphael.js.

You could make use of Raphael's element.getBBox(), which does the same thing as the native getBBox().

I too am having a hard time getting the JQuery syntax to work for me. This returned Uncaught TypeError: Object [object Object] has no method 'getBBox':

console.log($("#testtext").getBBox().width);

... because I had omitted the array index (thanks @Christian Vielma, below)!

However standard Javascript worked for me and I was able to display the width of the (in my case) RECT in the Chrome console:

console.log(document.getElementById("testtext").getBBox().width);

So you might try that instead.

Try Element.getBoundingClientRect(). It's from the html DOM, but works for me on SVG elements (without much transformation).

One thing to make sure is that your svg is added to the DOM and not detached. Also make sure that your SVG element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!