Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Get position between two points by given length

I have two points which are p1 and p2.

How can I get the position from p1 to p2 by a given length?

var p1 = {x: 100, y: 400};
var p2 = {x: 300, y: 500};
var len = 40;

enter image description here

like image 965
Thanh Nguyen Avatar asked Dec 08 '22 00:12

Thanh Nguyen


1 Answers

You can calculate the distance between the two points using Pythagoras's theorem:

var xDist = p2.x - p1.x;
var yDist = p2.y - p1.y;
var dist = Math.sqrt(xDist * xDist + yDist * yDist);

Then you calculate the fraction of the total distance covered by your length:

var fractionOfTotal = len / dist;

Finally you get the point you are looking for like this:

var p = {
   x: p1.x + xDist * fractionOfTotal,
   y: p1.y + yDist * fractionOfTotal
}

So let's say len covers 20 percent of the total distance. Then you add 20 percent of the x-distance to p1.x and 20 percent of the y-distance to p1.y.

like image 107
lex82 Avatar answered Dec 11 '22 09:12

lex82