Measure distance between polygon points SVG

1

I created a very simple% color 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 a two-point distance as in this example:

But I do not need to show the line and the number by marking the distance, I just need to return the value of the segment.

    
asked by anonymous 23.08.2014 / 19:26

1 answer

2

Assuming you already have the coordinates in JavaScript variables, just apply the Pythagorean Theorem:

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

By applying to your HTML, you can do this in browsers that support 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));

link

    
23.08.2014 / 19:40