Bresenham line generation not working? Making a line out of points

I want to figure out how to make a line out of a series of points for implementation in another project in p5js, I heard that bresenham line generation was probably the best way to do this, however in the sketch I’ve implemented it in the line only works past a 45 degree angle? Also, the line has an odd pixelated effect to it like the pixel and screen values don’t match.
If anyone has any ideas on how to fix this behavior or if there’s a better way to do this, I’d really appreciate the help! You can see the sketch here:
https://editor.p5js.org/tinywitchdraws/sketches/f6xvRJvVO

Hey,

Double check your code with the pseudo code from the Wikipedia article. There might be some minor adjustments to be made.

As far as pixelated effect, you can take a look at Xiaolin Wu’s line algorithm which can be used to minimize this effect by taking into account pixel color brightness when drawing the line.

I also cleaned up some of your code for more clarity. I removed the array in the function and just replaced it by calling point() directly to make the code run a little faster. Feel free to use it (or not).

Hope this helps!


function setup() {
  createCanvas(400, 400);
}

function draw() {
  background('white');
  strokeWeight(2);
  bresenham(3, 2, mouseX, mouseY);
}

// function for line generation
function bresenham(x1, y1 , x2, y2)
{
    var m_new = 2 * (y2 - y1);
    var slope_error_new = m_new - (x2 - x1);
     
    for (x = x1, y = y1; x <= x2; x++)
    {
      // document.write("(" +x + "," + y + ")<br>");
      point(x,y);
 
      // Add slope to increment angle formed
      slope_error_new += m_new;
 
      // Slope error reached limit, time to
      // increment y and update slope error.
      if (slope_error_new >= 0)
      {
          y+=1;
          slope_error_new -= 2 * (x2 - x1);
      }
    }
      
}

Take special note of this section of the Wikipedia article.

The integer based implementation of Bresenham that you are using only supports positive slopes that are less than 1:1 (if it is steeper or negative this algorithm will not work, so you have to do some finagling to handle those cases).