So I have a line, connecting two points, and I want to give this line a visual name in my canvas. I want this name to be positioned right at the middle of the line but with an offset so that the text doesn't go through the line. Determining the middle of the line isn't that hard you can just find it out like that:
And the line equation of the normal to the line can be determined pretty easy too:
Where you can find out n
just by inserting P
into the equation.
Now to the problem: For a given distance to the line, I want to find a point P(xn, yn)
that is on that normal to the line through the middle of the line. After inserting the linear function into the distance formula I end up with this:
Not only am I not able to transform this equation to get a valid value for xn
, I believe there has to be an mathematically easier way to achieve this.
Line middle is
mx = (x1 + x2)/2
my = (y1 + y2)/2
Line length is
len = sqrt((x1 - x2)^2 + (y1 - y2)^2)
Normalized direction vector of the line is
dx = (x2-x1) / len
dy = (y2-y1) / len
Perpendicular vector is
nx = -dy
ny = dx
Point at offset d
from middle is
px = mx + d * nx
py = mx + d * ny
or for other side
px = mx - d * nx
py = mx - d * ny