Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 825
Dave Mackey Avatar asked Dec 15 '15 03:12

Dave Mackey


People also ask

How do you fill a canvas in HTML?

The fill() method in HTML canvas is used to fill the current drawing path. The default is black. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.

How do you fill a circle in canvas?

The arc() method creates an arc/curve (used to create circles, or parts of circles). Tip: To create a circle with arc(): Set start angle to 0 and end angle to 2*Math. PI. Tip: Use the stroke() or the fill() method to actually draw the arc on the canvas.


1 Answers

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.

like image 138
John Bupit Avatar answered Oct 11 '22 00:10

John Bupit