Is there a way to fill a point until it hits the border using HTML Canvas and JavaScript?

I have an old code I'm working with. This happens something like this:

PAINT (200, 200), 2, 10

This basically means: fill the area starting at the coordinates: X 200 Y 200, with a dark green color, until the dot reaches the boundary color of light green, and then stop filling.

The idea is that you can draw a path (for example, a state) using one color, then fill the entire path with a different color. It does not fill the entire screen because the outline has a color at which filling stops.

+6
source share
1 answer

You can use Flood fill to fill the region. It takes a start point (or start point ) as input and recursively fills an area, trying 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 a function that checks if point (x, y) filled with a boundary color (in this case light green) 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.

In the above implementation, 4-connected is used . But it can easily be extended to 6 or 8-connected neighborhoods.

+2
source

All Articles