search

Home  >  Q&A  >  body text

javascript - How to determine if a point is within a triangle in js?

What mathematical formula is used?

巴扎黑巴扎黑2721 days ago1381

reply all(3)I'll reply

  • 滿天的星座

    滿天的星座2017-06-12 09:31:32

    Very common questions in computational geometry

    There are △ABC and point O(x, y). Let the triangle vertex coordinates be: A(x1,y1), B(x2,y2), C(x3,y3)

    Point O is in △ABC, and point O and point C are on the same side of straight line AB, then:

    [(x-x1)(y2-y1) - (y-y1)(x2-x1)][(x3-x1)(y2-y1) - (y3-y1)(x2-x1)] > 0

    Similarly, point O and point B are on the same side of straight line AC; point O and point A are on the same side of straight line BC.

    If the above three conditions are met, point O is within △ABC.


    Personally, I prefer this method because it only contains four arithmetic operations and size judgment, and does not involve operations such as trigonometric functions and square roots, so it is faster. If there is a better way, please advise.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-12 09:31:32

    Can be processed through Barycentric coordinate system.
    Reference link: https://en.wikipedia.org/wiki...

    Suppose the point to be tested is (x0, y0), and the three points of the triangle are (x1, y1), (x2, y2), (x3, y3)

    According to the definition of center of gravity coordinates:

    x0 = a * x1 + b * x2  + c * x3
    y0 = a * y1 + b * y2 + c * y3
    a + b + c = 1

    where a b c are three coefficients respectively. If and only if a b c are both greater than or equal to 0 and less than or equal to 1, point (x0, y0) is within the triangle formed by point (x1, y1), point (x2, y2) and point (x3, y3).

    From the above definition, we can get the solution of a b c:

    a = ((y2 - y3)*(x0 - x3) + (x3 - x2)*(y0 - y3)) / ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
    b = ((y3 - y1)*(x0 - x3) + (x1 - x3)*(y0 - y3)) / ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
    c = 1 - a - b

    Written in JS method:

    function pointInTriangle(x0, y0, x1, y1, x2, y2, x3, y3) {
      var pisor = (y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3);
      var a = ((y2 - y3)*(x0 - x3) + (x3 - x2)*(y0 - y3)) / pisor;
      var b = ((y3 - y1)*(x0 - x3) + (x1 - x3)*(y0 - y3)) / pisor;
      var c = 1 - a - b;
    
      return a >= 0 && a <= 1 && b >= 0 && b <= 1 && c >= 0 && c <= 1
    }

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-12 09:31:32

    This is not simple
    For example, point x has three angles a, b, and c of a triangle
    x is the vertex of an angle. If the sum of the three angles
    axb bxc cxa is 360 degrees, then point x is within the triangle

    There are many articles
    Search them
    http://www.cnblogs.com/baie/a...

    reply
    0
  • Cancelreply