微信小程序Canvas不支持 isPointInPath的解决方案

        近期在做一个贴纸功能,里面需要判断点击坐标是否处于贴纸范围,该贴纸经过了旋转和缩放。html5的canvas支持isPointInPath方法快速判断点击是否属于某多边形区域,但是微信小程序并不支持.

        研究了一番,使用了ray-crossing算法的判断方法如下(在边缘线的也算进去了):

function isPointInPolygon (point, target) {
    const targetSize = target.length;
    let nCross = 0;
    for (let i = 0; i < targetSize; i += 1) {
      const p1 = target[i];
      const p2 = target[(i + 1) % targetSize];

      if (point.y < Math.min(p1.y, p2.y)) continue;
      if (point.y > Math.max(p1.y, p2.y)) continue;

      if (p1.y == p2.y) {
        const minX = Math.min(p1.x, p2.x);
        const maxX = Math.max(p1.x, p2.x);
        if (point.y == p1.y && (point.x >= minX && point.x <= maxX)) {
          return true;
        }
      } else {
        const x = ((point.y - p1.y) * (p2.x - p1.x)) / (p2.y - p1.y) + p1.x;
        if (x == point.x) {
          return true;
        } else if (x > point.x) {
          nCross++;
        }
      }
    }

    return nCross % 2 == 1;
  }

参考文章:https://blog.csdn.net/yanjunmu/article/details/46723407