I have a graph where I have a polygon and a point. The graph is developed using a JS library called canvasjs. I am trying to find out the direction and distance a point is outside the polygon. I have managed to know if the point is inside or outside the polygon but struggling to find out the direction and distance if a point is outside the polygon. Or, how much to add or subtract the distance and in what direction so that the point falls inside the polygon.
The logic that I used to know if the point is inside or outside the polygon is mentioned below so that it can help others.
function area($x1, $y1, $x2, $y2, $x3, $y3)
{
return abs(($x1 * ($y2 - $y3) + $x2 * ($y3 - $y1) + $x3 * ($y1 - $y2)) / 2.0);
}
function check($x1, $y1, $x2, $y2, $x3,$y3, $x4, $y4, $x, $y)
{
// Calculate area of rectangle ABCD
$A = area($x1, $y1, $x2, $y2, $x3, $y3) + area($x1, $y1, $x4, $y4, $x3, $y3);
// Calculate area of triangle PAB
$A1 = area($x, $y, $x1, $y1, $x2, $y2);
// Calculate area of triangle PBC
$A2 = area($x, $y, $x2, $y2, $x3, $y3);
// Calculate area of triangle PCD
$A3 = area($x, $y, $x3, $y3, $x4, $y4);
// Calculate area of triangle PAD
$A4 = area($x, $y, $x1, $y1, $x4, $y4);
// Check if sum of A1, A2,
// A3 and A4 is same as A
return ($A == $A1 + $A2 + $A3 + $A4);
}
if (check(661, 2000, 50, 2000, 50, 775, 280, 775, $x, $y))
{
echo "yes";
}
else
{
echo "no";
}
Please comment if I need to add more information to my question so that is much clear.