Posted By

jatkins on 10/20/15


Tagged

math line algorithm lines Maths intersection Geometry intersect


Versions (?)

getIntersectionPointOfTwoLines


 / Published in: JavaScript
 

Released into the public domain by Josh Atkins, 2016.

  1. sniktaDraw.misc.getIntersectionPointOfTwoLines = function(line1, line2) {
  2. if(line1.gradient === 0 && line2.gradient === Infinity) { // line1 is horizontal; line2 is vertical
  3. return {x: line2.x, y: line1.y};
  4. }
  5. else if(line1.gradient === Infinity && line2.gradient === 0) { // line1 is vertical; line2 is horizontal
  6. return {x: line1.x, y: line2.y};
  7. }
  8. else if(!line1.orthogonalToAnAxis && line2.gradient === Infinity) { // line1 has a real, non-zero gradient; line2 is vertical
  9. return {x: line2.x, y: line1.gradient * line2.x + line1.yIntercept};
  10. }
  11. else if(!line1.orthogonalToAnAxis && line2.gradient === 0) { // line1 has a real, non-zero gradient; line2 is horizontal
  12. return {x: (line2.y - line1.yIntercept) / line1.gradient, y: line2.y};
  13. }
  14. else if(line1.gradient === Infinity && !line2.orthogonalToAnAxis) { // line1 has a vertical gradient; line2 has a real, non-zero gradient
  15. return {x: line1.x, y: line2.gradient * line1.x + line2.yIntercept};
  16. }
  17. else if(line1.gradient === 0 && !line2.orthogonalToAnAxis) { // line1 is horizontal; line2 has a real, non-zero gradient
  18. return {x: (line1.y - line2.yIntercept) / line2.gradient, y: line1.y};
  19. }
  20. else if(!line1.orthogonalToAnAxis && !line2.orthogonalToAnAxis) { // both lines have real, non-zero gradients and are of the form y=mx+c
  21. // Equate f(x)s and solve for x, then substitute x into either equation of the form 'y = mx + c'
  22.  
  23. var x = (line2.yIntercept - line1.yIntercept) / (line1.gradient - line2.gradient),
  24. y = line1.gradient * x + line1.yIntercept;
  25.  
  26. return {x: x, y: y};
  27. }
  28. };

Report this snippet  

You need to login to post a comment.