My goal was to develop a recursive function that would continue filling the empty spaces of a canvas until reaching the edges or encountering a different colored space.
function createFillingPoint() {
let x = points[0][0],
y = points[0][1];
var pattern = ctx.getImageData(x, y, 1, 1).data;
var colorToChange = rgbToHex(pattern);
ctx.fillRect(x, y, 1, 1);
colorFillRec(x + 1, y, width.value, height.value, colorToChange);
colorFillRec(x - 1, y, width.value, height.value, colorToChange);
colorFillRec(x, y + 1, width.value, height.value, colorToChange);
colorFillRec(x, y - 1, width.value, height.value, colorToChange);
}
This particular function initializes the starting point and identifies the original color to be changed throughout the recursion.
function colorFillRec(x, y, w, h, colorToChange) {
if (
x > w ||
x < 0 ||
y > h ||
y < 0 ||
rgbToHex(ctx.getImageData(x, y, 1, 1).data) != colorToChange
)
return;
ctx.fillRect(x, y, 1, 1);
colorFillRec(x + 1, y, w, h, colorToChange);
colorFillRec(x - 1, y, w, h, colorToChange);
colorFillRec(x, y + 1, w, h, colorToChange);
colorFillRec(x, y - 1, w, h, colorToChange);
}
This is the core recursive function. Both functions compare colors and halt execution if they differ from the original color.
Despite my attempts to run the function, I encountered the "Maximum call stack size exceeded" error... I struggled to come up with an alternative solution for achieving the desired outcome (whether through another recursive approach or not) but couldn't find one.