Skip to content

Commit 3bbb02f

Browse files
committed
Bresenham's line drawing algorithm added
1 parent f3fa1ba commit 3bbb02f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Bresenham's line drawing algorithm.
3+
* It has complexity O(n)
4+
* @param {number} x1 The first coordinate of the beginning of the line
5+
* @param {number} y1 The second coordinate of the beginning of the line
6+
* @param {number} x2 The first coordinate of the end of the line
7+
* @param {number} y2 The second coordinate of the end of the line
8+
*/
9+
function drawLine(x1, y1, x2, y2) {
10+
var dx = Math.abs(x2 - x1),
11+
dy = Math.abs(y2 - y1),
12+
cx = (x1 < x2) ? 1 : -1,
13+
cy = (y1 < y2) ? 1 : -1,
14+
error = dx - dy,
15+
doubledError;
16+
17+
while (x1 !== x2 || y1 !== y2) {
18+
drawPoint(x1, y1);
19+
doubledError = error + error;
20+
if (doubledError > -dy) {
21+
error -= dy;
22+
x1 += cx;
23+
}
24+
if (doubledError < dx) {
25+
error += dx;
26+
y1 += cy;
27+
}
28+
}
29+
}
30+
31+
/**
32+
* Draws (prints) the given coordinates
33+
* @param {number} x The first coordinate of the point
34+
* @param {number} y The second coordinate of the point
35+
*/
36+
function drawPoint(x, y) {
37+
console.log(x, y);
38+
}

0 commit comments

Comments
 (0)