简体   繁体   English

Javascript中点画线算法

[英]Javascript Midpoint Line Drawing Algorithm

I'm drawing a line in javascript using the Midpoint Algorithm Line Drawing.我正在使用中点算法线图在 javascript 中绘制一条线。 When the line is in a descent trajectory, it computes the wrong values.当该线处于下降轨迹时,它会计算错误的值。 Can somebody help me?有人可以帮助我吗?

data input //midline(1,6,8,4);数据输入 //中线(1,6,8,4);

function midline(x0, y0, x1, y1) {
  /* Using midpoint algorithm for lines. */
  const dx = x1 - x0;
  const dy = y1 - y0;
  var d = 2 * dy - dx;
  const incrE = 2 * dy;
  const incrNE = 2 * (dy - dx);
  var x = x0;
  var y = y0;

  var output = [];

  //listeners
  console.log("dy = ", dy, "dx = ", dx);
  console.log("d = ", d);
  console.log("incrE = ", incrE);
  console.log("incrNE = ", incrNE);
  console.log("----------------------------------");

  while (x <= x1) {
    // if not the last x
    console.log("x = ", x, " y = ", y);
    output.push([x,y]);


    if (d <= 0) {
      console.log("E");

      d = d + incrE;
      x++;
    } else {
      console.log("NE");

      d = d + incrNE;
      x++;
      y++;
    }
  }
  console.table(output);
}

在此处输入图片说明

If per my comment the Mid Point Line Drawing algorithm is only suited for the first quadrant, that is...如果根据我的评论中点线绘制算法仅适用于第一象限,那就是......

 x0 < x1 and y0 < y1

...must hold true, then adjustments are required if x1 < x0 or y1 < y0. ...必须成立,如果 x1 < x0 或 y1 < y0,则需要进行调整。

Taking the case presented (1,6) - (8,4), this is a downward slope because y1 < y0 (ie, 4 < 6 ).以 (1,6) - (8,4) 的情况为例,这是一个向下的斜率,因为 y1 < y0 (即 4 < 6 )。 To make this a workable case for the Mid Point Line Drawing algorithm, you can simply negate the y values, in which case y0 < y1 will then hold true.为了使其成为中点线绘制算法的可行案例,您可以简单地否定 y 值,在这种情况下 y0 < y1 将成立。 Of course, when capturing the results, the values need to then be adjusted by multiplying by -1 again.当然,在捕获结果时,需要再次乘以-1 来调整值。 So, suggest wedging in the following before putting x0, y0, x1, and y1 to use...因此,建议在使用 x0、y0、x1 和 y1 之前插入以下内容...

let xReflect = 1;
if ( x1 < x0 ) {
    x0 = -x0;
    x1 = -x1;
    xReflect = -1;
}

let yReflect = 1;
if ( y1 < y0 ) {
    y0 = -y0;
    y1 = -y1;
    yReflect = -1;
}

...and then, when pushing the output to the array, you will need to perform the following... ...然后,将输出推送到数组时,您需要执行以下操作...

output.push( [ x * xReflect, y * yReflect ] );

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM