I'm preparing for an interview where I think they could ask me to modify the app I wrote to handle diagonal line drawing.
The simple program can draw a canvas in the terminal and then add shapes to it.
The following C 20 4
will create:
----------------------
| |
| |
| |
| |
----------------------
Now I'm trying to handle diagonal lines so that L 2 1 11 4
(that's two points represented as x1, y1, x2, y2) results in:
----------------------
| x |
| x |
| x |
| x |
----------------------
At least that's how I think it should look. I tried both answers from here: Bresenham algorithm in Javascript
So the apply
function looks like this:
apply(canvas) {
const dx = Math.abs(this.x2 - this.x1);
const dy = Math.abs(this.y2 - this.y1);
const sx = (this.x1 < this.x2) ? 1 : -1;
const sy = (this.y1 < this.y2) ? 1 : -1;
let err = dx - dy;
let x1 = this.x1;
let y1 = this.y1;
let x2 = this.x2;
let y2 = this.y2;
canvas.pixels[y1][x1] = 'x';
while(true) {
canvas.pixels[y1][x1] = 'x';
if ((x1 === x2) && (y1 === y2)) break;
const e2 = 2 * err;
if (e2 > -dy) { err -= dy; x1 += sx; }
if (e2 < dx) { err += dx; y1 += sy; }
}
}
But what I'm getting back is too many iterations on the x so the line is too thick:
----------------------
| xx |
| xxx |
| xxx |
| xx |
----------------------
Here is a runnable demo: https://repl.it/@DominicTobias/Bresenhams-line-algo
Type C 20 4
, hit Enter, then L 2 1 11 4
.
Any help appreciated!