function getMC(p) { var m = (p[1][1] - p[0][1]) / (p[1][0] - p[0][0]); var c1 = p[0][1]-m*p[0][0]; var c2 = p[1][1]-m*p[1][0]; //console.log("Slop", m, "C1", c1, "C2", c2) if(Math.round(c1)!==Math.round(c2)) throw new Error("Something is not right"); return [m,c1]; } function getIntersectionPoint(points){ var line1 = getMC([points[0],points[1]]); var line2 = getMC([points[2],points[3]]); if(line1[0]===line2[0] && line1[1]===line2[1]){ console.log("same line"); return ("same line"); } else if(line1[0]===line2[0]){ console.log("parallel line"); return ("parallel line"); } else { var x=((line2[1]-line1[1])/(line1[0]-line2[0])); var iX = Math.round(x); var y1=(line1[0]*x + line1[1]); var y2=(line2[0]*x + line2[1]); //console.log("Intersection point", "X", Math.round(x), "y1", Math.round(y1), "y2", Math.round(y2)); if(Math.round(y1)!==Math.round(y2)) throw new Error("Something is not right"); var iY=Math.round(y1); var l1Status=""; var l2Status=""; if(iX>=points[0][0]){ if(iX<=points[1][0]){ l1Status="on L1 line segment"; } else{ l1Status="on L1 line forward side"; } } else { l1Status="on L1 line back side"; } if(iX>=points[2][0]){ if(iX<=points[3][0]){ l2Status="on L2 line segment"; } else{ l2Status="on L2 line forward side"; } } else { l2Status="on L2 line back side"; } console.log("Intersection point ("+ iX+", "+ iY+") is "+l1Status+" and "+l2Status); return ("Intersection point ("+ iX+", "+ iY+") is "+l1Status+" and "+l2Status); } } /* var points = [[15,10],[49,25],[29,5],[32,32]]; // intersacting getIntersectionPoint(points); var points = [[30,15],[50,25],[30,10],[50,20]] // parallel line getIntersectionPoint(points); var points = [[20,10],[30,15],[40,20],[50,25]] // same line getIntersectionPoint(points); var points = [[21,-4],[27,8],[40,20],[50,25]] // intersacting getIntersectionPoint(points); var points = [[21,-4],[31,8],[40,20],[50,25]] // intersacting getIntersectionPoint(points); */