forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19_3_flood_fill.html
More file actions
59 lines (50 loc) · 1.8 KB
/
19_3_flood_fill.html
File metadata and controls
59 lines (50 loc) · 1.8 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
50
51
52
53
54
55
56
57
58
59
<!doctype html>
<base href="http://eloquentjavascript.net/">
<script src="code/chapter/19_paint.js"></script>
<script>
// Call a given function for all horizontal and vertical neighbors
// of the given point.
function forAllNeighbors(point, fn) {
fn({x: point.x, y: point.y + 1});
fn({x: point.x, y: point.y - 1});
fn({x: point.x + 1, y: point.y});
fn({x: point.x - 1, y: point.y});
}
// Given two positions, returns true when they hold the same color.
function isSameColor(data, pos1, pos2) {
var offset1 = (pos1.x + pos1.y * data.width) * 4;
var offset2 = (pos2.x + pos2.y * data.width) * 4;
for (var i = 0; i < 4; i++) {
if (data.data[offset1 + i] != data.data[offset2 + i])
return false;
}
return true;
}
tools["Flood fill"] = function(event, cx) {
var startPos = relativePos(event, cx.canvas);
var data = cx.getImageData(0, 0, cx.canvas.width,
cx.canvas.height);
// An array with one place for each pixel in the image.
var alreadyFilled = new Array(data.width * data.height);
// This is a list of same-colored pixel coordinates that we have
// not handled yet.
var workList = [startPos];
while (workList.length) {
var pos = workList.pop();
var offset = pos.x + data.width * pos.y;
if (alreadyFilled[offset]) continue;
cx.fillRect(pos.x, pos.y, 1, 1);
alreadyFilled[offset] = true;
forAllNeighbors(pos, function(neighbor) {
if (neighbor.x >= 0 && neighbor.x < data.width &&
neighbor.y >= 0 && neighbor.y < data.height &&
isSameColor(data, startPos, neighbor))
workList.push(neighbor);
});
}
};
</script>
<link rel="stylesheet" href="css/paint.css">
<body>
<script>createPaint(document.body);</script>
</body>