forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19_4_proper_lines.html
More file actions
49 lines (44 loc) · 1.31 KB
/
19_4_proper_lines.html
File metadata and controls
49 lines (44 loc) · 1.31 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
48
49
<!doctype html>
<base href="https://eloquentjavascript.net/">
<script src="code/chapter/19_paint.js"></script>
<div></div>
<script>
function drawLine(from, to, color) {
let points = [];
if (Math.abs(from.x - to.x) > Math.abs(from.y - to.y)) {
if (from.x > to.x) [from, to] = [to, from];
let slope = (to.y - from.y) / (to.x - from.x);
for (let {x, y} = from; x <= to.x; x++) {
points.push({x, y: Math.round(y), color});
y += slope;
}
} else {
if (from.y > to.y) [from, to] = [to, from];
let slope = (to.x - from.x) / (to.y - from.y);
for (let {x, y} = from; y <= to.y; y++) {
points.push({x: Math.round(x), y, color});
x += slope;
}
}
return points;
}
function draw(pos, state, dispatch) {
function connect(newPos, state) {
let line = drawLine(pos, newPos, state.color);
pos = newPos;
dispatch({picture: state.picture.draw(line)});
}
connect(pos, state);
return connect;
}
function line(pos, state, dispatch) {
return end => {
let line = drawLine(pos, end, state.color);
dispatch({picture: state.picture.draw(line)});
};
}
let dom = startPixelEditor({
tools: {draw, line, fill, rectangle, pick}
});
document.querySelector("div").appendChild(dom);
</script>