Thanh Nguyen
Thanh Nguyen

Reputation: 5342

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

Upvotes: 5

Views: 3405

Answers (1)

lex82
lex82

Reputation: 11297

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.

Upvotes: 15

Related Questions