Chito Cheng
Chito Cheng

Reputation: 550

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/

Upvotes: 6

Views: 19951

Answers (2)

Bo. Ga.
Bo. Ga.

Reputation: 148

For anyone trying to know if in 2020 :
JQUERY (3.4.1) >> $('#lineID').get(0).getTotalLength()
JS >> document.getElementById('lineID').getTotalLength()
works on <lines/>
the answer is yes.

Browsers tested :
Firefox 76.0.1
Chromium: 81.0.4044.138 (Official Build) (64-bit)
Chrome 83.0.4103.61
Opera 68.0.3618.125

https://jsfiddle.net/mzyd4ura/2/

Upvotes: 6

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

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

Upvotes: 15

Related Questions