29

I need to get the dimension on the screen of a <path> in a SVG from JavaScript.

I do not have any "transformation" or "scaling" (transform, scale) on my SVG. The only thing changed is the viewBox, which will change the size of all the elements in the SVG.

I have been using myPath.getBBox(), the width returned stays the same even though I change my viewBox.

So I'm wondering what is the relation with this viewBox and size of a path. Maybe there is a function to compute the width?

jsgoupil
  • 3,788
  • 3
  • 38
  • 53
  • I think you need to be slightly more precise: you want the _bounding box dimensions_, right? And do you want these in SVG coordinates or screen coordinates? – Phrogz Aug 11 '11 at 22:50

2 Answers2

57

You can call getBoundingClientRect() method on your path to get dimensions. It will return a ClientRect object:

var w = myPath.getBoundingClientRect().width;
var h = myPath.getBoundingClientRect().height;

There is also a getScreenCTM() method, which returns the transformation matrix in the current screen pixels of the element it was called on. the spec says:

[getScreenCTM()] Returns the transformation matrix from current user units (i.e., after application of the ‘transform’ attribute, if any) to the parent user agent's notice of a "pixel". [...] Note that null is returned if this element is not hooked into the document tree.

Spadar Shut
  • 15,111
  • 5
  • 47
  • 54
2

First off all, keep in mind that path cannot have a width. Its a set of coords. The browser uses that info along with the drawing method to connect the coords and create a visible shape.

Secondly, the bounding box is a snapshot of when the SVG was rendered. That is why you don't get the updated width on resize.

A workaround I guess would be to get the width of the conatiner element to the SVG (div or something else).

Maybe some of the libraries may provide some utility method to figure this out.

Mrchief
  • 75,126
  • 20
  • 142
  • 189