判断一个点是否落在多边形区域内
<pre><code class="language-javascript">/**
* 判断一个点是否落在多边形区域内
* @param {*} polygon
* @param {*} pointX
* @param {*} pointY
* @returns polygon---组成多边形的点 [x1, y1, x2, y2, x3, y3, ...]
*/
export function ContainsPoint(polygon, pointX, pointY) {
const n = polygon.length &gt;&gt; 1;
let ax, lup;
let ay = polygon[2 * n - 3] - pointY;
let bx = polygon[2 * n - 2] - pointX;
let by = polygon[2 * n - 1] - pointY;
if (bx === 0 &amp;&amp; by === 0) return false; // point on edge
// let lup = by &gt; ay;
for (let ii = 0; ii &lt; n; ii++) {
ax = bx;
ay = by;
bx = polygon[2 * ii] - pointX;
by = polygon[2 * ii + 1] - pointY;
if (bx === 0 &amp;&amp; by === 0) return false; // point on edge
if (ay === by) continue;
lup = by &gt; ay;
}
let depth = 0;
for (let i = 0; i &lt; n; i++) {
ax = bx;
ay = by;
bx = polygon[2 * i] - pointX;
by = polygon[2 * i + 1] - pointY;
if (ay &lt; 0 &amp;&amp; by &lt; 0) continue; // both 'up' or both 'down'
if (ay &gt; 0 &amp;&amp; by &gt; 0) continue; // both 'up' or both 'down'
if (ax &lt; 0 &amp;&amp; bx &lt; 0) continue; // both points on the left
if (ay === by &amp;&amp; Math.min(ax, bx) &lt; 0) return true;
if (ay === by) continue;
const lx = ax + ((bx - ax) * -ay) / (by - ay);
if (lx === 0) return false; // point on edge
if (lx &gt; 0) depth++;
if (ay === 0 &amp;&amp; lup &amp;&amp; by &gt; ay) depth--; // hit vertex, both up
if (ay === 0 &amp;&amp; !lup &amp;&amp; by &lt; ay) depth--; // hit vertex, both down
lup = by &gt; ay;
}
return (depth &amp; 1) === 1;
}</code></pre>