javascript 如何获得 svg 线元素总长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32493871/
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
How to get a svg line element total length
提问by Chito Cheng
I have a very simple svg with just one line on it
我有一个非常简单的 svg,上面只有一行
<svg version="1.1" id="animation" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 640 480" xml:space="preserve" preserveAspectRatio="xMinYMin meet" baseProfile="tiny">
<line id="line-1" style="stroke:#777777;stroke-miterlimit:10;" x1="358" y1="332.5" x2="371.3" y2="364.7"/>
</svg>
and I use jquery to get the line and find it length with getTotalLength()
我使用 jquery 来获取该行并使用 getTotalLength() 找到它的长度
var len = $("#line-1").get(0).getTotalLength();
but my browser keeps giving this error warning
但我的浏览器不断发出此错误警告
Uncaught TypeError: $(...).get(...).getTotalLength is not a function
未捕获的类型错误:$(...).get(...).getTotalLength 不是函数
Can anyone tell me if line element can use getTotalLength()? If not, how can I get the length of the line.
谁能告诉我线元素是否可以使用 getTotalLength()?如果没有,我怎样才能得到线的长度。
Thanks.
谢谢。
here's my example: https://jsfiddle.net/chitocheng/1h5eckjh/
回答by Spencer Wieczorek
A line
doesn't store the length so you need to get it yourself using the distance formula:
Aline
不存储长度,因此您需要使用距离公式自己获取它:
var line = $("#line-1").get(0);
var len = dist(line.x1.baseVal.value, line.x2.baseVal.value,
line.y1.baseVal.value, line.y2.baseVal.value);
$("#len").text(len);
function dist(x1, x2, y1, y2){
return Math.sqrt( (x2-=x1)*x2 + (y2-=y1)*y2 );
}
But a path
does support the getTotalLength()
function. So if you want to use it you need to use a <path>
rather then a <line>
. To setup your <line>
as a <path>
you can do:
但是 apath
确实支持该getTotalLength()
功能。所以如果你想使用它,你需要使用 a<path>
而不是 a <line>
。要将您设置<line>
为<path>
您可以执行以下操作:
<path id="line-1" style="stroke:#777777;stroke-miterlimit:10;" d="M 358,332.5 L 371.3,364.7"/>