Ой, надо ж подкрепить свою функцию тестом.
<body style="padding: 0px; margin: 0px;">
<canvas id="canvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById( 'canvas' );
var ctx = canvas.getContext( '2d' );
var triangle = [
{ x: 200, y: 50 },
{ x: 160, y: 240 },
{ x: 60, y: 100 }
];
function isPointInTriangle ( x, y, x1, y1, x2, y2, x3, y3 ) {
return (
( y-y1 ) * ( x2-x1 ) > ( x-x1 ) * ( y2-y1 ) &&
( y-y2 ) * ( x3-x2 ) > ( x-x2 ) * ( y3-y2 ) &&
( y-y3 ) * ( x1-x3 ) > ( x-x3 ) * ( y1-y3 ) );
}
function renderTest ( mouseX, mouseY ) {
ctx.clearRect( 0, 0, canvas.width, canvas.height );
ctx.lineWidth = 2;
ctx.fillStyle = isPointInTriangle( mouseX, mouseY,
triangle[0].x, triangle[0].y,
triangle[1].x, triangle[1].y,
triangle[2].x, triangle[2].y ) ? 'red' : 'blue';
ctx.beginPath();
ctx.moveTo( triangle[0].x, triangle[0].y );
ctx.lineTo( triangle[1].x, triangle[1].y );
ctx.lineTo( triangle[2].x, triangle[2].y );
ctx.fill();
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.moveTo( mouseX + 3, mouseY );
ctx.arc( mouseX, mouseY, 3, 0, Math.PI*2, false );
ctx.fill();
}
canvas.addEventListener( 'mousemove', function ( event ) {
renderTest( event.pageX, event.pageY );
}, false );
renderTest( -100, -100 );
</script>
</body>