javascript 获取SVG中路径的尺寸

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7032403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:45:42  来源:igfitidea点击:

Get dimension of a path in SVG

javascriptsvgbounding-box

提问by jsgoupil

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

我需要从 JavaScript 获取 SVG 中 <path> 屏幕上的尺寸。

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.

我的 SVG 上没有任何“转换”或“缩放”(转换、缩放)。唯一改变的是 viewBox,它将改变 SVG 中所有元素的大小。

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

我一直在使用 myPath.getBBox(),即使我更改了 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?

所以我想知道这个 viewBox 和路径的大小有什么关系。也许有一个函数来计算宽度?

回答by Spadar Shut

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

您可以getBoundingClientRect()在路径上调用方法来获取尺寸。它将返回一个ClientRect对象:

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()方法,它返回在它被调用的元素的当前屏幕像素中的变换矩阵。规范

[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.

[getScreenCTM()] 将转换矩阵从当前用户单元(即,在应用“转换”属性之后,如果有的话)返回到父用户代理的“像素”通知。[...] 请注意,如果此元素未挂钩到文档树中,则返回 null。

回答by Mrchief

First off all, keep in mind that pathcannot 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.

首先,请记住,path不能有宽度。它是一组坐标。浏览器使用该信息和绘图方法来连接坐标并创建一个可见的形状。

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.

其次,边界框是渲染 SVG 时的快照。这就是为什么你在调整大小时没有得到更新的宽度。

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

我想一种解决方法是将 conatiner 元素的宽度设置为 SVG (div或其他东西)。

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

也许某些可能会提供一些实用方法来解决这个问题。