forked from mgechev/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbresenham-line-drawing.js
More file actions
47 lines (42 loc) · 1.28 KB
/
bresenham-line-drawing.js
File metadata and controls
47 lines (42 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
(function (exports) {
'use strict';
/**
* Bresenham's line drawing algorithm.
* It has complexity O(n)
* @param {number} x1 The first coordinate of the beginning of the line
* @param {number} y1 The second coordinate of the beginning of the line
* @param {number} x2 The first coordinate of the end of the line
* @param {number} y2 The second coordinate of the end of the line
* @param {function} draw Optional custom drawing function.
*/
function drawLine(x1, y1, x2, y2, draw) {
drawPoint = draw || drawPoint;
var dx = Math.abs(x2 - x1);
var dy = Math.abs(y2 - y1);
var cx = (x1 < x2) ? 1 : -1;
var cy = (y1 < y2) ? 1 : -1;
var error = dx - dy;
var doubledError;
while (x1 !== x2 || y1 !== y2) {
drawPoint(x1, y1);
doubledError = error + error;
if (doubledError > -dy) {
error -= dy;
x1 += cx;
}
if (doubledError < dx) {
error += dx;
y1 += cy;
}
}
}
/**
* Draws (prints) the given coordinates
* @param {number} x The first coordinate of the point
* @param {number} y The second coordinate of the point
*/
function drawPoint(x, y) {
console.log(x, y);
}
exports.drawLine = drawLine;
}(typeof exports === 'undefined' ? window : exports));