-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
82 lines (63 loc) · 1.47 KB
/
index.js
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module.exports = {
drawLines,
drawLine,
setPixel
};
function drawLines(context, lines) {
var imageData = getImageData(context);
lines.forEach(function(line) {
drawLine(imageData, line);
});
putImageData(context, imageData);
}
function drawLine(imageData, line) {
const { start, end, color } = line;
bresenhamPoints(start.x, start.y, end.x, end.y).forEach(function(point) {
setPixel(imageData, color, point);
});
return imageData;
}
function setPixel(imageData, color, point) {
var { data, width } = imageData;
var [r, g, b, a] = color;
var { x, y } = point;
var offset = (y * width + x) * 4;
data[offset] = r;
data[offset + 1] = g;
data[offset + 2] = b;
data[offset + 3] = a;
return imageData;
}
function getImageData(context) {
var { width, height } = context.canvas;
return context.getImageData(0, 0, width, height);
}
function putImageData(context, imageData) {
context.putImageData(imageData, 0, 0);
return context;
}
function bresenhamPoints(x0, y0, x1, y1) {
var dx = delta(x1, x0);
var dy = delta(y1, y0);
var sx = x0 < x1 ? 1 : -1;
var sy = y0 < y1 ? 1 : -1;
var err = dx - dy;
var lines = [];
while (true) {
lines.push({ x: x0, y: y0 });
if (x0 === x1 && y0 === y1) break;
var e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
return lines;
}
function delta(first, second) {
return Math.abs(first - second);
}