Skip to content

Instantly share code, notes, and snippets.

@garymcm
Created January 11, 2022 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garymcm/80b7db73d4ae802caea787dc0f45eb33 to your computer and use it in GitHub Desktop.
Save garymcm/80b7db73d4ae802caea787dc0f45eb33 to your computer and use it in GitHub Desktop.
/**
* Bresenhams line algorithm for integers.
* @see https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm#Algorithm_for_integer_arithmetic
*/
function plotLine(x0, y0, x1, y1) {
/** Step direction on the x-axis */
let sx = x0 < x1 ? 1 : -1
/** Step direction on the y-axis */
let sy = y0 < y1 ? 1 : -1
let dx = Math.abs(x1 - x0)
let dy = -Math.abs(y1 - y0)
/** error value e_xy, which is balanced between x and y coords */
let err = dx + dy
while (true) {
// Each coordinate
console.log(x0, y0)
if (x0 == x1 && y0 == y1) break
let e2 = 2 * err
if (e2 >= dy) {
/* e_xy+e_x > 0 */
err += dy
x0 += sx
}
if (e2 <= dx) {
/* e_xy+e_y < 0 */
err += dx
y0 += sy
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment