6

I have some old basic code I'm working with. It goes something like this:

PAINT (200, 200), 2, 10

This means essentially: fill an area beginning at coordinates: X 200 Y 200 with the color dark green until the point reaches a boundary color of light green, then stop filling.

The idea is that one can draw an outline (say of a state) using one color then fill the entire outline with another color. It doesn't fill the whole screen because the outline is of the color at which the fill stops.

Dave Mackey
  • 4,306
  • 21
  • 78
  • 136
  • 1
    so if you were to "fill the entire outline", does it do so in a scanning motion? like line by line? if so, how is the starting point determined? how does it handle concave shapes? – thedarklord47 Dec 15 '15 at 03:08
  • Possible duplicate of [How can I perform flood fill with HTML Canvas?](http://stackoverflow.com/questions/2106995/how-can-i-perform-flood-fill-with-html-canvas) – Reinstate Monica -- notmaynard Dec 15 '15 at 15:47

1 Answers1

3

You can use Flood fill to fill a region. It takes a starting point (or the seed point) as an input and recursively fills the region, by attempting to fill its empty neighbors.

A simple stack-based implementation in JavaScript:

// Takes the seed point as input
var floodfill = function(point) {
    var stack = Array();
    stack.push(point); // Push the seed
    while(stack.length > 0) {
        var currPoint = stack.pop();
        if(isEmpty(currPoint)) { // Check if the point is not filled
            setPixel(currPoint); // Fill the point with the foreground
            stack.push(currPoint.x + 1, currPoint.y); // Fill the east neighbour
            stack.push(currPoint.x, currPoint.y + 1); // Fill the south neighbour
            stack.push(currPoint.x - 1, currPoint.y); // Fill the west neighbour
            stack.push(currPoint.x, currPoint.y - 1); // Fill the north neighbour
        }
    }
};

isEmpty(point) is the function that tests whether the point (x, y) is filled with the boundary color (light green, in this case) or not.

setPixel(point) fills the point (x, y) with the foreground color (dark green, in your case).

The implementation of these functions is trivial, and I leave it to you.

The implementation above uses a 4-connected neighborhood. But it can easily be extended to 6 or 8-connected neighborhoods.

Community
  • 1
  • 1
John Bupit
  • 10,406
  • 8
  • 39
  • 75
  • Thanks for the helpful answer! I'm a little confused on one point, I don't see how this knows what the boundary color is or the foreground color? – Dave Mackey Dec 18 '15 at 05:25
  • 1
    You could pass the background and foreground colors to the function as well, and have your `isEmpty` and `setPixel` use the same. – John Bupit Dec 21 '15 at 15:21