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;
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With