Get all pixel coordinates between 2 points

后端 未结 3 1318
我寻月下人不归
我寻月下人不归 2021-02-04 13:20

I want to get all the x,y coordinates between 2 given points, on a straight line. While this seems like such an easy task, I can\'t seem to get my head around it.

So, fo

3条回答
  •  没有蜡笔的小新
    2021-02-04 14:01

    Based on the wiki article, here's my JS code which handles both high and low lines:

    const drawLine = (x0, y0, x1, y1) => {
      const lineLow = (x0, y0, x1, y1) => {
        const dx = x1 - x0
        let dy = y1 - y0
        let yi = 1
    
        if (dy < 0) {
          yi = -1
          dy = -dy
        }
    
        let D = 2 * dy - dx
        let y = y0
    
        for (let x = x0; x < x1; x++) {
          drawPoint(x, y)
    
          if (D > 0) {
            y = y + yi
            D = D - 2 * dx
          }
    
          D = D + 2 * dy
        }
      }
    
      const lineHigh = (x0, y0, x1, y1) => {
        let dx = x1 - x0
        const dy = y1 - y0
        let xi = 1
    
        if (dx < 0) {
          xi = -1
          dx = -dx
        }
    
        let D = 2 * dx - dy
        let x = x0
    
        for (let y = y0; y < y1; y++) {
          drawPoint(x, y)
    
          if (D > 0) {
            x = x + xi
            D = D - 2 * dy
          }
    
          D = D + 2 * dx
        }
      }
    
      const { abs } = Math
    
      if (abs(y1 - y0) < abs(x1 - x0)) {
        if (x0 > x1) {
          lineLow(x1, y1, x0, y0)
        } else {
          lineLow(x0, y0, x1, y1)
        }
      } else {
        if (y0 > y1) {
          lineHigh(x1, y1, x0, y0)
        } else {
          lineHigh(x0, y0, x1, y1)
        }
      }
    }
    

提交回复
热议问题