Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a svg line element total length

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/

like image 822
Chito Cheng Avatar asked Dec 02 '22 14:12

Chito Cheng


1 Answers

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

like image 153
Spencer Wieczorek Avatar answered Dec 09 '22 21:12

Spencer Wieczorek