Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get bounding box for SVG path using jQuery

Tags:

svg

jquery-svg

I want to get the getBBox() for svg path in jquery. i tried like this

$("#"+ path id)[0].getBBox() -> returns x=0,y=0,width=0,height=0

I have added the path to an SVG element. I tried some other element in SVG, for example text node in that case it returns the some bounding box value.

How can I calculate the bounding box for a path in SVG?

<path id="container_svg_John_0" fill="none" stroke-width="3" stroke="url(#container_svg_John0Gradient)" stroke-linecap="butt" stroke-linejoin="round" d="M -2390.2 -125.8888888888889 L 0 0 M 0 0 L 251.60000000000002 -45.77777777777778 M 251.60000000000002 -45.77777777777778 L 503.20000000000005 -11.444444444444445 M 503.20000000000005 -11.444444444444445 L 629 -183.11111111111111 "/>
like image 337
SivaRajini Avatar asked May 04 '13 17:05

SivaRajini


2 Answers

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.

like image 181
Robert Longson Avatar answered Oct 02 '22 08:10

Robert Longson


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

like image 26
nicholaswmin Avatar answered Oct 02 '22 09:10

nicholaswmin