关于javascript:计算直角多边形分割点

32次阅读

共计 1510 个字符,预计需要花费 4 分钟才能阅读完成。

有一个多边形 (p0,p1,p2…pn), 每一边平行于 X 轴或者 Y 轴,先给定数值 K , 以 P0 为起始点将 N 边形分成 K 段,每一段长度相等,求等分点 (T0,T1,T2…Tk)
`

   /**
   * @function 获取直角坐标系多边形等分点
   * @param {array} [[1,1], [1,3], [3,3], [3,4], [5,4], [5,1]]
   *
   */
  function getAvgCoordinatePointsBy(polygon, k) {const C = polygon.reduce((calc, currentPoint, index) => {
      // 获取相邻连接点
      const nextPoint =
        index === polygon.length - 1 ? polygon[0] : polygon[index + 1];
      // 计算连接点的长度
      const length = Math.abs(nextPoint[0] - currentPoint[0] + (nextPoint[1] - currentPoint[1])
      );
      return calc + length;
    }, 0);

    // 均匀长度
    const svgLen = C / k;

    // 等分点第一个点就是多边形起始点
    const res = [polygon[0]];
    let arr = polygon;
    // 已知第一个的等分点,在计算 k - 1 个点的坐标
    for (let i = 1; i < k; i++) {arr = getPoint(arr, svgLen);
      res.push(arr[0])
    }


    return res;
  }

  /**
   * @function 依据坐标路线获取指定长度的起点
   *
   */
  function getPoint(arr, length) {
    let res;
    let total = 0;
    for (let i = 0; i < arr.length; i++) {const curPoi = arr[i];
      const nextIndex = i === arr.length - 1 ? 0 : i + 1;
      const nextPoi = arr[nextIndex];
      // 有一个必为 0,所以不须要在算差值的时候加绝对值
      const diffX = curPoi[0] - nextPoi[0];
      const diffY = curPoi[1] - nextPoi[1];

      const len = Math.abs(diffX + diffY);
      // 如果上一次循失去的总长度加上这次两点之间的间隔比指定长度长的话,起点就在 arr[i] 和 arr[nextIndex] 之间
      if (total + len >= length) {
        let point;
        const diffLen = length - total; // 残余须要的长度
        if (diffX === 0) {
          // 如果两点 X 坐标差值为 0,则以 Y 轴坐标算间隔
          // 依据正负号判断位移方向
          const y =
            nextPoi[1] - curPoi[1] >= 0
              ? curPoi[1] + diffLen
              : curPoi[1] - diffLen;
          const x = curPoi[0];
          point = [x, y];
        } else {
          // 如果两点 Y 坐标差值为 0,则以 X 轴坐标算间隔
          // 依据正负号判断位移方向
          const x =
            nextPoi[0] - curPoi[0] >= 0
              ? curPoi[0] + diffLen
              : curPoi[0] - diffLen;
          const y = curPoi[1];
          point = [x, y];
        }


        res = [point, ...arr.slice(i + 1)];
        // 如果第 1、第 2 个元素相等,阐明起点在拐点,去重
        if (res.length > 1 && res[0][0] === res[1][0] && res[0][1] === res[1][1]) {res.shift();
        }
        break;
      }

      total += len;
    }

    return res;
  }
  `

正文完
 0