Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dimension of a path in SVG

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?

like image 637
jsgoupil Avatar asked Aug 11 '11 20:08

jsgoupil


People also ask

How do you find the width and height of SVG?

To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method. const el = document. getElementById("yourElement"); const rect = el.

Does SVG have width and height?

SVG's exported from Illustrator CC are 'responsive' by default, in other words there is no height or width attributes, no dimensions.

What is M in SVG path?

The following commands are available for path data: M = moveto. L = lineto. H = horizontal lineto. V = vertical lineto.


1 Answers

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.

like image 92
Spadar Shut Avatar answered Oct 12 '22 19:10

Spadar Shut