I try to create a recursive function to fill all the empty space of a canvas until the edges or when there is already an other color filled.
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);
}
Basically, this function creates the first point and gives the original color that the function has to change.
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 function is the recursive one. Both functions check the pixel’s color, if it is different as the original color the function stops.
I tried to run the function but I got the “Maximum call stack size exceeded” error…
I tried to find a new way to get the right result (with another recursive or not recursive function) but I couldn’t.
martinfo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.