Excellent article on determining if a point is in a triangle.

Point in triangle test

I needed a javascript version of the Barycentric coordinate method. Here is the function:

function is_in_triangle (px,py,ax,ay,bx,by,cx,cy){

```
``` //credit: http://www.blackpawn.com/texts/pointinpoly/default.html

var v0 = [cx-ax,cy-ay];

var v1 = [bx-ax,by-ay];

var v2 = [px-ax,py-ay];

var dot00 = (v0[0]*v0[0]) + (v0[1]*v0[1]);

var dot01 = (v0[0]*v1[0]) + (v0[1]*v1[1]);

var dot02 = (v0[0]*v2[0]) + (v0[1]*v2[1]);

var dot11 = (v1[0]*v1[0]) + (v1[1]*v1[1]);

var dot12 = (v1[0]*v2[0]) + (v1[1]*v2[1]);

var invDenom = 1/ (dot00 * dot11 - dot01 * dot01);

var u = (dot11 * dot02 - dot01 * dot12) * invDenom;

var v = (dot00 * dot12 - dot01 * dot02) * invDenom;

return ((u >= 0) && (v >= 0) && (u + v < 1));

}

Thanks for the code, now I’m pretty handy.

does this only work for right angle triangles?

It works for any triangle. You pass in the test point and the three points that define your triangle.

Thanks for this beautiful piece of code. I have a hard time converting math to code, so this was a god sent. Thanks again 🙂

Very helpful!