Point in Triangle
geometryfunctionjavascriptarchivedTriangle bounds test
A simple method for dermining if a 2D coordinate, x,y falls inside of the bounds of the triangle described by the points p1, p2, p3.
function pointInTriangle(x, y, p1, p2, p3)
{
var alpha = ((p2[1] - p3[1]) * (x - p3[0]) + (p3[0] - p2[0]) * (y - p3[1])) /
((p2[1] - p3[1]) * (p1[0] - p3[0]) + (p3[0] - p2[0]) * (p1[1] - p3[1]));
var beta = ((p3[1] - p1[1]) * (x - p3[0]) + (p1[0] - p3[0]) * (y - p3[1])) /
((p2[1] - p3[1]) * (p1[0] - p3[0]) + (p3[0] - p2[0]) * (p1[1] - p3[1]));
var gamma = 1 - alpha - beta;
return (alpha>0 && beta>0 && gamma>0);
}
Example source code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ctx = null, game = null;
var mouseX = -1, mouseY = -1;
var isOver = false;
var triangle = [ [150, 100], [400, 150], [250, 280] ];
window.onload = function() {
game = document.getElementById('game');
ctx = game.getContext('2d');
game.addEventListener('mousemove', function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
// Calculate actual mouse position on Canvas
var p = game;
do
{
mouseX-= p.offsetLeft;
mouseY-= p.offsetTop;
p = p.offsetParent;
} while(p!=null);
// See if cursor is over the rectangle...
isOver = pointInTriangle(mouseX, mouseY,
triangle[0], triangle[1], triangle[2]);
});
requestAnimationFrame(drawGame);
};
function pointInTriangle(x, y, p1, p2, p3)
{
var alpha = ((p2[1] - p3[1]) * (x - p3[0]) + (p3[0] - p2[0]) * (y - p3[1])) /
((p2[1] - p3[1]) * (p1[0] - p3[0]) + (p3[0] - p2[0]) * (p1[1] - p3[1]));
var beta = ((p3[1] - p1[1]) * (x - p3[0]) + (p1[0] - p3[0]) * (y - p3[1])) /
((p2[1] - p3[1]) * (p1[0] - p3[0]) + (p3[0] - p2[0]) * (p1[1] - p3[1]));
var gamma = 1 - alpha - beta;
return (alpha>0 && beta>0 && gamma>0);
}
function drawGame()
{
if(ctx==null) { return; }
// Set fill and stroke colours dependant on whether or not the
// cursor is over the triangle
if(isOver)
{
ctx.fillStyle = "#ff9999";
ctx.strokeStyle = "#ff3333";
}
else
{
ctx.fillStyle = "#aaaacc";
ctx.strokeStyle = "#7777aa";
}
// Draw the triangle
ctx.beginPath();
ctx.moveTo(triangle[0][0], triangle[0][1]);
ctx.lineTo(triangle[1][0], triangle[1][1]);
ctx.lineTo(triangle[2][0], triangle[2][1]);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Request the next animation frame
requestAnimationFrame(drawGame);
}
</script>
</head>
<body>
<p>Move your mouse cursor on and off the triangle below.</p>
<p>If you do not see a triangle, check your browser supports Canvas elements, and has Javascript enabled.</p>
<canvas id="game" width="600" height="400"></canvas>
</body>
</html>