@codeguppy I have been unable to run the CodeGuppy demo on flood fill for reasons I do not understand. It worked just fine in the editor used in the video, but fails to run as expected in a p5.js web editor. The following source code was taken from the middle of the video using imageData from the canvas context and right before animation was added. A similar question was posted on StackOverFlow:
https://stackoverflow.com/questions/76645668/flood-fill-algorithm-only-coloring-outside-of-the-area-trying-to-be-filled
Source code:
let imageData;
function setup() {
createCanvas(800, 800);
}
function draw() {
if (mouseIsPressed) {
line(floor(pmouseX), floor(pmouseY), floor(mouseX), floor(mouseY));
}
}
function keyPressed() {
imageData = drawingContext.getImageData(0, 0, 800, 800);
flood(floor(mouseX), floor(mouseY));
drawingContext.putImageData(imageData, 0, 0);
}
function flood(x, y) {
let fillStack = [];
fillStack.push([x, y]);
while (fillStack.length > 0) {
let [x, y] = fillStack.pop();
if (!valid(x, y)) {
continue;
}
if (isPixel(x, y)) {
continue;
}
setPixel(x, y);
fillStack.push([x + 1, y]);
fillStack.push([x - 1, y]);
fillStack.push([x, y - 1]);
fillStack.push([x, y + 1]);
}
}
// Does not work in p5.js web editor
function setPixel(x, y) {
let pixels = imageData.data;
let i = (y * width + x) * 4;
pixels[i] = 255; // red
pixels[i + 1] = 0; // green
pixels[i + 2] = 0; // blue
pixels[i + 3] = 255; // alpha
}
// Does not work in p5.js web editor
function isPixel(x, y) {
let pixels = imageData.data;
let i = (y * width + x) * 4;
return pixels[i + 3] > 0;
}
function valid(x, y) {
return x >= 0 && x <= width - 1 && y >= 0 && y <= height - 1;
}
Unexpected output not seen in the video:
As you can see the background is red and not the drawing. There is a chance that I have copied the source code incorrectly, but it is similar to what was posted on StackOverflow. The video is an excellent video which shows why _not to use recursive functions and demonstrates alternate techniques: https://www.youtube.com/watch?v=a7qCVxq-dWE
I’m at a loss to explain why it worked so well in the video but I am unable to get the same result in p5.js web editor. I’m hoping that it is just a typo or some minor problem which can be fixed. Thanks for your time and outstanding work.
Addendum:
I had to change the name of the ‘fill’ function to ‘flood’ because the editor complained that ‘fill’ was being used for something else.