has-intersection
v0.0.3
Published
Return true if two line segments have intersection.
Downloads
4
Readme
has-intersection
Return true if two line segments have intersection.
Install
npm install has-intersection
Usage
// [x , y, x', y']
var lineA = [-5, 5, 5,-5];
var lineB = [ 5, 5,-5,-5]
if(hasIntersection(lineA, lineB)){
console.log("They have!");
}
Code
module.exports = hasIntersection =function(lineA,lineB) {
var x1 = lineA[0];
var y1 = lineA[1];
var f1 = lineA[2] - lineA[0];
var g1 = lineA[3] - lineA[1];
var x2 = lineB[0];
var y2 = lineB[1];
var f2 = lineB[2] - lineB[0];
var g2 = lineB[3] - lineB[1];
var det = f2 * g1 - f1 * g2;
if (det == 0) {
return false;
}
var dx = x2 - x1;
var dy = y2 - y1;
var t1 = (f2*dy - g2*dx)/det;
var t2 = (f1*dy - g1*dx)/det;
if (t1 > 0 && t1 < 1 && t2 > 0 && t2 < 1){
return {x : x1 + f1*t1, y : y1 + g1*t1};
}else{
return false;
}
};