Javascript: Is Point In Triangle

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));
}

Advertisements
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

5 Responses to Javascript: Is Point In Triangle

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

  2. chris says:

    does this only work for right angle triangles?

    • Dimitri Tishchenko says:

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

  3. Anders says:

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s