JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas"></canvas>
JavaScript
function coordsAreInside(point, polyVerts) {
var j = polyVerts.length - 1,
oddNodes = false,
polyY = [], polyX = [],
x = point[0],
y = point[1];
for (var s = 0; s < polyVerts.length; s++) {
polyX.push(polyVerts[s][0]);
polyY.push(polyVerts[s][1]);
};
for (var i = 0; i < polyVerts.length; i++) {
if ((polyY[i]< y && polyY[j]>=y
|| polyY[j]< y && polyY[i]>=y)
&& (polyX[i]<=x || polyX[j]<=x)) {
oddNodes^=(polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x);
}
j=i;
}
return oddNodes;
}
//--------------------------------
// POLYGONS
var poly1 = [ // this one works
[156, 85],
[283, 82],
[304, 154],
[276, 183],
[202, 197],
[142, 147],
[140, 118]
];
function poly1draw() {
ctx.beginPath();
ctx.moveTo(156, 85)
ctx.lineTo(283, 82);
ctx.lineTo(304, 154);
ctx.lineTo(276, 183);
ctx.lineTo(202, 197);
ctx.lineTo(142, 147);
ctx.lineTo(140, 118);
ctx.fill();
}
var poly2 = [ // this one doesn't
[223, 165],
[296, 156],
[420, 261],
[395, 398],
[384, 283],
[255, 202]
];
function poly2draw() {
ctx.beginPath();
ctx.moveTo(223, 165)
ctx.lineTo(296, 156);
ctx.lineTo(420, 261);
ctx.lineTo(395, 398);
ctx.lineTo(384, 283);
ctx.lineTo(255, 202);
ctx.fill();
}
var mPos = [0, 0]; // mouse point
var ctx;
function setup() {
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth,
canvas.height = window.innerHeight;
ctx = canvas.getContext("2d");
document.addEventListener('mousemove', onDocumentMouseMove, false);
}
function onDocumentMouseMove(event) {
mPos = [event.clientX, event.clientY];
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (!coordsAreInside(mPos, poly1)) { poly1draw(); }
if...