Skip to content

Commit 6fe7b4b

Browse files
committed
Chapter 19 - Proper lines: Draw working
1 parent daaef44 commit 6fe7b4b

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

chapter-19/proper-lines.html

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<!DOCTYPE html>
2+
<meta charset="utf-8" />
3+
<script src="paint.js"></script>
4+
5+
<div></div>
6+
<script>
7+
function draw(pos, state, dispatch) {
8+
let prev = pos;
9+
function drawPixel(pos, state) {
10+
line(prev, pos, state, dispatch);
11+
if (pos != prev) {
12+
prev = pos;
13+
}
14+
}
15+
drawPixel(pos, state);
16+
return drawPixel;
17+
}
18+
19+
const aroundDiag = [
20+
{ dx: -1, dy: 0 },
21+
{ dx: 1, dy: 0 },
22+
{ dx: 0, dy: -1 },
23+
{ dx: 0, dy: 1 },
24+
{ dx: -1, dy: -1 },
25+
{ dx: -1, dy: 1 },
26+
{ dx: 1, dy: -1 },
27+
{ dx: 1, dy: 1 },
28+
];
29+
30+
function line(start, end, state, dispatch) {
31+
const fullDistance = Math.floor(Math.sqrt((start.x - end.x) ** 2 + (start.y - end.y) ** 2));
32+
const drawn = [{ x: start.x, y: start.y, color: state.color, distance: fullDistance }];
33+
34+
for (let done = 0; done < drawn.length; done++) {
35+
const distances = [];
36+
for (let { dx, dy } of aroundDiag) {
37+
const x = drawn[done].x + dx;
38+
const y = drawn[done].y + dy;
39+
distances.push({ x, y, distance: Math.sqrt((x - end.x) ** 2 + (y - end.y) ** 2) });
40+
}
41+
const minDistance = distances.reduce(
42+
(min, curr) => (curr.distance < fullDistance && curr.distance < min.distance ? curr : min),
43+
distances[0]
44+
);
45+
if (drawn[done].distance > minDistance.distance) {
46+
drawn.push({ x: minDistance.x, y: minDistance.y, color: state.color, distance: minDistance.distance });
47+
}
48+
}
49+
dispatch({ picture: state.picture.draw(drawn) });
50+
}
51+
52+
let dom = startPixelEditor({
53+
tools: { draw, line, fill, rectangle, pick },
54+
});
55+
document.querySelector('div').appendChild(dom);
56+
</script>

0 commit comments

Comments
 (0)