calculating the point of intersection of two lines

前端 未结 5 1196
栀梦
栀梦 2020-12-05 21:16

I have dynamically generated lines that animate and I want to detect when a lines hits another. I\'m trying to implement some basic linear algebra to obtain the equation of

5条回答
  •  爱一瞬间的悲伤
    2020-12-05 21:59

    You may do as follows;

    function lineIntersect(a,b){
      a.m = (a[0].y-a[1].y)/(a[0].x-a[1].x);  // slope of line 1
      b.m = (b[0].y-b[1].y)/(b[0].x-b[1].x);  // slope of line 2
      return a.m - b.m < Number.EPSILON ? undefined
                                        : { x: (a.m * a[0].x - b.m*b[0].x + b[0].y - a[0].y) / (a.m - b.m),
                                            y: (a.m*b.m*(b[0].x-a[0].x) + b.m*a[0].y - a.m*b[0].y) / (b.m - a.m)};
    }
    
    var line1 = [{x:3, y:3},{x:17, y:8}],
        line2 = [{x:7, y:10},{x:11, y:2}];
    console.log(lineIntersect(line1, line2));

提交回复
热议问题