Measure distance between SVG polygon points

Asked

Viewed 176 times

1

I created a SVG very simple with a triangle.

<svg class="triangulo" height="210" width="500">
   <polygon points="200,10 250,190 160,210" style="fill:lime;stroke:purple;stroke-width:1" />
</svg>

And what I want to know is how to make a script that results in the distance of two points as in this example:

However I do not need to appear the line and the number demarcating the distance, I just need to return the value of the segment.

1 answer

2


Assuming you already have coordinates in Javascript variables, just apply the Pythagorean theorem:

var d = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));

Applying to your HTML, you can do this in the browsers that support the SVG DOM:

var triangulo = document.querySelector('.triangulo polygon');

// Os dois primeiros pontos do triângulo
var p1 = triangulo.points[0];
var p2 = triangulo.points[1];
// Distância entre esses dois pontos
var d = Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));

http://jsfiddle.net/owu7w92n/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.