Javascript: Find point on perpendicular line always the same distance away

自古美人都是妖i 提交于 2019-12-19 10:05:34

问题


I'm trying to find a point that is equal distance away from the middle of a perpendicular line. I want to use this point to create a Bézier curve using the start and end points, and this other point I'm trying to find.

I've calculated the perpendicular line, and I can plot points on that line, but the problem is that depending on the angle of the line, the points get further away or closer to the original line, and I want to be able to calculate it so it's always X units away.

Take a look at this JSFiddle which shows the original line, with some points plotted along the perpendicular line:

http://jsfiddle.net/eLxcB/1/.

If you change the start and end points, you can see these plotted points getting closer together or further away.

How do I get them to be uniformly the same distance apart from each other no matter what the angle is?

Code snippit below:

// Start and end points
var startX = 120
var startY = 150
var endX = 180
var endY = 130

// Calculate how far above or below the control point should be
var centrePointX = ((startX + endX) / 2);
var centrePointY = ((startY + endY) / 2);

// Calculate slopes and Y intersects
var lineSlope = (endY - startY) / (endX - startX);
var perpendicularSlope = -1 / lineSlope;
var yIntersect = centrePointY - (centrePointX * perpendicularSlope);

// Draw a line between the two original points
R.path('M '+startX+' '+startY+', L '+endX+' '+endY);

回答1:


Generally you can get the coordinates of a normal of a line like this:

P1 = {r * cos(a) + Cx, -r * sin(a) + Cy},
P2 = {-r * cos(a) + Cx, r * sin(a) + Cy}.

A demo applying this to your case at jsFiddle.



来源:https://stackoverflow.com/questions/17989148/javascript-find-point-on-perpendicular-line-always-the-same-distance-away

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!