Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  135] [ 4]  / answers: 1 / hits: 18971  / 9 Years ago, thu, september 10, 2015, 12:00:00

I have a very simple svg with just one line on it



<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()



var len = $(#line-1).get(0).getTotalLength();


but my browser keeps giving this error warning




Uncaught TypeError: $(...).get(...).getTotalLength is not a function




Can anyone tell me if line element can use getTotalLength()? If not, how can I get the length of the line.



Thanks.



here's my example: https://jsfiddle.net/chitocheng/1h5eckjh/


More From » jquery

 Answers
8

A line doesn't store the length so you need to get it yourself using the distance formula:



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 );
}


Fiddle Example



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:



<path id=line-1 style=stroke:#777777;stroke-miterlimit:10; d=M 358,332.5 L 371.3,364.7/>


Fiddle Path Example


[#65119] Tuesday, September 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;