SOURCE

console 命令行工具 X clear

                    
>
console
const pnpoly = (point, areas) => {
    const num = areas.length - 1;
    let flag = false;
    for (let i = 0, j = num - 1; i < num; j = i++) {
        const isBelowOrAbove =
            (areas[i][1] > point[1] && areas[j][1] > point[1]) ||
            (areas[i][1] < point[1] && areas[j][1] < point[1]);
        if (
            isBelowOrAbove &&
            point[0] <
            ((areas[j][0] - areas[i][0]) * (point[1] - areas[i][1])) /
            (areas[j][1] - areas[i][1]) +
            areas[i][0]
        ) {
            flag = !flag;
        }
    }
    return flag;
};

const input = [[10, 20], [30, 10], [40, 40], [20, 40]];
const point = [10, 45]

console.log(pnpoly(point, input));

const ctx = canvas.getContext("2d");
ctx.save();
canvas.width = 500;
canvas.height = 500;
input.forEach((i, index) => {
    const [x, y] = [i[0] * 10, i[1] * 10];
    if (index === 0) {
        ctx.moveTo(x, y);
    } else {
        ctx.lineTo(x, y)
    }
});
ctx.closePath();
ctx.lineWidth = 1;
ctx.strokeStyle = "#333";
ctx.stroke();

ctx.restore();
ctx.beginPath();
ctx.arc(point[0] * 10, point[1] * 10, 2, 0, 2 * Math.PI);
ctx.fillStyle = "#000";
ctx.fill();
<canvas id="canvas"></canvas>
#canvas {
    width: 500px;
    height: 500px;
    background: #ffd0002a;
}