Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...