# 矩形是否包含点

只要判断该点的横坐标和纵坐标是否夹在矩形的左右边和上下边之间;

但是多边形就比较复杂了。 实现代码:

/**
 * 判断 pt 是否在 ring 组成的多边形内
 * @param {*} pt 点,[0, 100]
 * @param {*} ring 组成面的坐标点,[[0, 0], [0, 100], [100, 100], [100, 0], [0, 0]]
 * <returns>true:在面内;false:不在面内</returns>
 */
function booleanPointInPolygon(pt, ring, ignoreBoundary = false) {
  const bboxArr = inBBox(ring)
  if (!bboxArr) {
    return false
  }
  let isInside = false
  if (ring[0][0] === ring[ring.length - 1][0] && ring[0][1] === ring[ring.length - 1][1]) {
    ring = ring.slice(0, ring.length - 1)
  }
  for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
    const xi = ring[i][0]
    const yi = ring[i][1]
    const xj = ring[j][0]
    const yj = ring[j][1]
    // 叉乘判断
    const onBoundary = (pt[1] * (xi - xj) + yi * (xj - pt[0]) + yj * (pt[0] - xi) === 0) && ((xi - pt[0]) * (xj - pt[0]) <= 0) && ((yi - pt[1]) * (yj - pt[1]) <= 0)
    if (onBoundary) {
      return !ignoreBoundary
    }
    const intersect = ((yi > pt[1]) !== (yj > pt[1])) && (pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi)
    if (intersect) {
      isInside = !isInside
    }
  }
  return isInside
}
function inBBox(pt, ring) {
  const bbox = getBbox(ring)
  return bbox[0] <= pt[0] && bbox[1] <= pt[1] && bbox[2] >= pt[0] && bbox[3] >= pt[1]
}
function getBbox(ring) {
  let xMin, xMax, yMin, yMax
  const xArr = []
  const yArr = []
  ring.forEach(point => {
    console.log(point[0])
    xArr.push(point[0])
    yArr.push(point[1])
  })
  xMin = Math.min.apply(Math, xArr)
  xMax = Math.max.apply(Math, xArr)
  yMin = Math.min.apply(Math, yArr)
  yMax = Math.max.apply(Math, yArr)
  return [xMin, xMax, yMin, yMax]
}

评 论:

更新: 11/21/2020, 7:00:56 PM