## Posted By

jatkins on 10/20/15

# getIntersectionPointOfTwoLines

/ Published in: JavaScript   Released into the public domain by Josh Atkins, 2016.

`sniktaDraw.misc.getIntersectionPointOfTwoLines = function(line1, line2) {    if(line1.gradient === 0 && line2.gradient === Infinity) { // line1 is horizontal; line2 is vertical        return {x: line2.x, y: line1.y};    }    else if(line1.gradient === Infinity && line2.gradient === 0) { // line1 is vertical; line2 is horizontal        return {x: line1.x, y: line2.y};    }    else if(!line1.orthogonalToAnAxis && line2.gradient === Infinity) { // line1 has a real, non-zero gradient; line2 is vertical        return {x: line2.x, y: line1.gradient * line2.x + line1.yIntercept};    }    else if(!line1.orthogonalToAnAxis && line2.gradient === 0) { // line1 has a real, non-zero gradient; line2 is horizontal        return {x: (line2.y - line1.yIntercept) / line1.gradient, y: line2.y};    }    else if(line1.gradient === Infinity && !line2.orthogonalToAnAxis) { // line1 has a vertical gradient; line2 has a real, non-zero gradient        return {x: line1.x, y: line2.gradient * line1.x + line2.yIntercept};    }    else if(line1.gradient === 0 && !line2.orthogonalToAnAxis) { // line1 is horizontal; line2 has a real, non-zero gradient        return {x: (line1.y - line2.yIntercept) / line2.gradient, y: line1.y};    }    else if(!line1.orthogonalToAnAxis && !line2.orthogonalToAnAxis) { // both lines have real, non-zero gradients and are of the form y=mx+c        // Equate f(x)s and solve for x, then substitute x into either equation of the form 'y = mx + c'         var x = (line2.yIntercept - line1.yIntercept) / (line1.gradient - line2.gradient),            y = line1.gradient * x + line1.yIntercept;         return {x: x, y: y};    }};`