最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - javascript - Get position between two points by given length - Stack Overflow

programmeradmin0浏览0评论

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;

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;

Share Improve this question asked Dec 19, 2015 at 16:20 Thanh NguyenThanh Nguyen 5,35212 gold badges44 silver badges75 bronze badges 6
  • 1 Wouldn't it just be p1.x + len ? – adeneo Commented Dec 19, 2015 at 16:21
  • If p1.y = p2.y, I think. @adeneo – Thanh Nguyen Commented Dec 19, 2015 at 16:23
  • Are you tried eval(p1.x + len) ? – Avinash Commented Dec 19, 2015 at 16:25
  • Oh, I see. Your diagram isn't representing the data. You should be using the Pythagorean theorem. – user1106925 Commented Dec 19, 2015 at 16:27
  • You should probably have "tilted" the lines in the drawing a little, to make the point clearer. – adeneo Commented Dec 19, 2015 at 16:29
 |  Show 1 more ment

1 Answer 1

Reset to default 16

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.

发布评论

评论列表(0)

  1. 暂无评论