Skip to content

Instantly share code, notes, and snippets.

@mikeesto
Created November 1, 2021 23:22
Show Gist options
  • Save mikeesto/2da3c1eb85b24d74d5f04ace5f2edbd3 to your computer and use it in GitHub Desktop.
Save mikeesto/2da3c1eb85b24d74d5f04ace5f2edbd3 to your computer and use it in GitHub Desktop.
Bresenham's Line Algorithm - Produces a list of points from start to end
function get_line(start, end) {
let [x1, y1] = start;
let [x2, y2] = end;
let dx = x2 - x1;
let dy = y2 - y1;
const is_steep = Math.abs(dy) > Math.abs(dx);
// Rotate line
if (is_steep) {
[x1, y1] = [y1, x1];
[x2, y2] = [y2, x2];
}
// Swap start and end points if necessary and store swap state
let swapped = false;
if (x1 > x2) {
[x1, x2] = [x2, x1];
[y1, y2] = [y2, y1];
swapped = true;
}
// Recalculate differences
dx = x2 - x1;
dy = y2 - y1;
let error = Math.floor(dx / 2.0);
let ystep = -1;
if (y1 < y2) {
ystep = 1;
}
// Iterate over bounding box generating points between start and end
let y = y1;
const points = [];
for (let i = x1; i <= x2; i++) {
let coord = [y, i];
if (!is_steep) {
coord = [i, y];
}
points.push(coord);
error -= Math.abs(dy);
if (error < 0) {
y += ystep;
error += dx;
}
}
if (swapped) {
points.reverse();
}
return points;
}
let points = get_line([0, 0], [3, 4]);
console.log(points);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment