Noam
Noam

Reputation: 617

Why does this recursive function get me a "Maximum call stack size exceeded" error?

I'm creating a paint app with HTML canvas and I'm trying to implement a "paint bucket" tool that would detect any neighboring pixels with the same color as the pixel which was clicked upon, and fill it with a new color.

I'm getting an "Uncaught RangeError: Maximum call stack size exceeded", but I can't figure out what's wrong with my logic:

function fillTool(){
    theCanvas.mousedown(function(e){
        var baseColor = paintUtilities.getPixelColor(e.offsetX, e.offsetY);
        context.fillStyle = color;
        fillNeighbors(e.offsetX, e.offsetY, baseColor);
    });
}

function fillNeighbors(x, y, baseColor) {
    context.fillRect(x, y, 1, 1);
    if (x > 0 && paintUtilities.getPixelColor(x - 1, y) === baseColor) {
        fillNeighbors(x - 1, y, baseColor);
    }
    if (y > 0 && paintUtilities.getPixelColor(x, y - 1) === baseColor) {
        fillNeighbors(x, y - 1, baseColor);
    }
    if (x < theCanvas.attr("width") - 1 && paintUtilities.getPixelColor(x + 1, y) === baseColor) {
        fillNeighbors(x + 1, y, baseColor);
    }   
    if (y < theCanvas.attr("height") - 1 && paintUtilities.getPixelColor(x, y + 1) === baseColor) {
        fillNeighbors(x, y + 1, baseColor);
    }   

}

Upvotes: 3

Views: 374

Answers (2)

Hamza Kubba
Hamza Kubba

Reputation: 2269

Actually on second look, I see the problem with your code, and it does have infinite recursion!

Let's say you start at x = 1, and x can go from 0 to 2. You first go left, and call the function recursively. That function will eventually go to the right! Then that cycle will repeat, forever. You need to track where you've visited, or pass the recursive function a direction to not go on, or something along those lines.

Upvotes: 1

Alek
Alek

Reputation: 11

Because it is a recursive function and in each if statement you call it again and again and again... that function has no base case.

Upvotes: 0

Related Questions