1

so I was looking around for line algorithms, when I found Bresenham's Algorithm. I decided to make a code version of it, and for the most part, it worked. However, when I wanted to draw a square, I ran into a problem. It won't draw a certain line. Here is my code (I should mention I'm using p5.js):

function drline(xs, ys, xe, ye) {
 if(xs == xe && ys == ye){
   point(xs, ys);
 } else {
   var df = (ye - ys) / (xe - xs);
   var lf = 0;
   var tf = 0;
   var is = 0;
   for(var i = xs; i <= xe; i++){
     tf = i - xs;
     lf = df * tf;
     is = lf+ys;
     console.log("X: " + i + ", Y: " + is);
     point(i, is);
   }
 }
}

function init(){
  createCanvas(700, 600);
  background(80);
  stroke(100, 200, 255);

}

function setup(){
 init();
 drline(300, 100, 400, 100);
 drline(300,200, 400, 200);
 drline(300, 100, 300, 200);
}

I also noticed the last value that was on the console was X: 300, Y: NaN. Sorry if this sounds kinda nooby, but I'm not sure what the issue is. Thank you in advance! :)

scunliffe
  • 62,582
  • 25
  • 126
  • 161

1 Answers1

1

You have a "Divide By Zero" error.

In your last line:

 drline(300, 100, 300, 200);
        ^xs       ^xe

I'm presuming xs = xStart, and xe = xEnd

on this line you are trying to calculate the angle... but if xs and xe are equal you end up with a 0 (zero) denominator.

 var df = (ye - ys) / (xe - xs);

As such you will get an NaN as it is not a possible calculation.

You will need to add a special condition in your logic that if((xe - xs) == 0){...} (e.g. a vertical rise with no run, or "undefined" slope) and handle this accordingly.

scunliffe
  • 62,582
  • 25
  • 126
  • 161