Find the length of a segment that is part of another segment

2 segments are given. You need to determine whether the points of one segment belong to another. And what is the length of this third segment. I do it as follows:

        function Point2f(start, type, end) {
            if(type == '-') {
                return {x: start.x - end.x, y: start.y - end.y}
            }
            else if(type == '*') {
                return {x: start.x * end.x, y: start.y * end.y}
            }
            else if(type == '+') {
                return {x: start.x + end.x, y: start.y + end.y}
            }
            else if(type == '/') {
                return {x: start.x / end.x, y: start.y / end.y}
            }
        }
        
        
        function intersection(start1, end1, start2, end2) {
            var dir1 = Point2f(end1, '-', start1)
            , dir2 = Point2f(end2, '-', start2);
            
            //считаем уравнения прямых проходящих через отрезки
            var a1 = -dir1.y;
            var b1 = +dir1.x;
            var d1 = -(a1*start1.x + b1*start1.y);
            
            var a2 = -dir2.y;
            var b2 = +dir2.x;
            var d2 = -(a2*start2.x + b2*start2.y);
            
            //подставляем концы отрезков, для выяснения в каких полуплоскотях они
            var seg1_line2_start = a2*start1.x + b2*start1.y + d2;
            var seg1_line2_end = a2*end1.x + b2*end1.y + d2;
            
            var seg2_line1_start = a1*start2.x + b1*start2.y + d1;
            var seg2_line1_end = a1*end2.x + b1*end2.y + d1;
            
            // один отрезок лежит на другом отрезке
            if (seg1_line2_start * seg1_line2_end == 0 || seg2_line1_start * seg2_line1_end == 0){
                return true;
            } 
        }    

How to determine the length?

Author: arttry, 2020-09-07

1 answers

So, you have determined that both segments belong to the same straight line.

Next, you need to determine the relative position of the ends. To do this, the easiest way is to choose a coordinate whose end difference is nonzero - for example, if dir1.x != 0 is the x-coordinate.

Then just sort the x-coordinates of the ends, and you get the relative position on the line. We need to consider all the cases and, accordingly, get a mysterious "third segment" - perhaps we mean the intersection, the general part, if it exists.

    A     B      первый отрезок
С D              варианты для второго отрезка, их 6, если не считать совпадения концов за отдельные случаи
C      D
C            D
      C D
      C      D
             C D
 1
Author: MBo, 2020-09-07 15:30:39