2

Like this (it's not accurate) Zoom in on drawn lines

How can I change the Bresenham line algorithm to keep cycling into itself and create this effect: (Drawning not accurate)

I have the basic line with 2 coordinates:

drawBresenhamLine = function (x0, y0, x1, y1) {

    var dx, dy, e2, err, sx, sy;
    console.log('Called LBR : ' + x0 + ',' + y0 + '->' + x1 + ',' + y1);
    dx = Math.abs(x1 - x0);
    sx = x0 < x1 ? 1 : -1;
    dy = Math.abs(y1 - y0);
    sy = y0 < y1 ? 1 : -1;
    err = (dx > dy ? dx : -dy) / 2;
    while (true) {
        //console.log('Push : '+x0 +' ,'+ y0);
        setPixel(x0, y0);
        setEnd(x1,y1);
        if (x0 === x1 && y0 === y1) {
            break;
        }
        e2 = err;
        if (e2 > -dx) {
            err -= dy;
            x0 += sx;

        }
        if (e2 < dy) {
            err += dx;
            y0 += sy;

        }

    }

    return null;
};

setPixel(x,y) changes the current pixel and drawBresenhamLine will use its coords next iteration.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Diego Vallejo
  • 55
  • 1
  • 7

2 Answers2

1

Suppose you have two variables defining the size of your canvas: canvasWidth and canvasHeight. Whenever you increment x or y just test against these variables:

if (e2 > -dx) {
    err -= dy;
    x0 += sx;

    // check against sides of canvas:
    if(x0 >= canvasWidth)
       x0 = 0;
    else if(x0 < 0)
       x0 = canvasWidth - 1;
}
if (e2 < dy) {
    err += dx;
    y0 += sy;

    // check against top and bottom of canvas:
    if(y0 >= canvasHeight)
       y0 = 0;
    else if(y0 < 0)
       y0 = canvasHeight - 1;
}

This assumes that the minimum x and y values are 0. If not then you can define a min and max x and y defining your canvas extent and test against those instead.

samgak
  • 23,944
  • 4
  • 60
  • 82
0

// Bresenham's line algorithm Try this retail function :

function drawLine(x0, y0, x1, y1) {
  var dx = Math.abs(x1 - x0),
      sx = x0 < x1 ? 1 : -1,
      dy = Math.abs(y1 - y0),
      sy = y0 < y1 ? 1 : -1,
      err = dx > dy ? dx : -dy;

  while (x0 != x1 || y0 != y1) {
      setPixel(x0, y0);
      var e2 = err;
      if (e2 > -dx * 2) {
          err -= dy;
          x0 += sx;
     }
     if (e2 < dy * 2) {
         err += dx;
         y0 += sy;
    }
  }
}

Using a canvas for the test issue, regards ;).

https://codepen.io/anon/pen/qPXOrJ