我正在遵循有关实现洪水填充算法的教程(https://www.youtube.com/watch?v=a7qCVxq-dWE),我认为我的代码看起来与我关注的人完全相同,但我的代码不工作,而他的工作。我正在绘制的圆圈的外部被填充,而内部由于某种原因保持白色。然后我无法填充多个圆圈/其他绘图。我是一个相当新的编码人员,其中一些内容有点超出了我的能力,我确信有更好或更有效的方法来实现洪水填充,但这是我遇到的最详细的教程。谢谢
我回顾了教程,我无法说出有什么不同,但这是迄今为止我的代码,以及正在发生的事情和应该发生的事情的图像。谢谢!
let imageData;
function setup() {
createCanvas(1000, 1000);
}
function draw() {
drawing();
}
function drawing() {
if (mouseIsPressed) {
line(pmouseX, pmouseY, mouseX, mouseY);
}
}
function keyPressed() {
imageData = drawingContext.getImageData(0, 0, 1000, 1000);
floodFilling(mouseX, mouseY);
drawingContext.putImageData(imageData, 0, 0);
}
function floodFilling(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]);
}
}
//set color of pixel
function setPixel(x, y) {
let pixels = imageData.data;
let i = (y * width + x) * 4;
pixels[i] = 255;
pixels[i + 1] = 0;
pixels[i + 2] = 0;
pixels[i + 3] = 255;
}
//make sure it has color
function isPixel(x, y) {
let pixels = imageData.data;
let i = (y * width + x) * 4;
return pixels[i + 3] > 0;
}
//make sure it is in bounds of canvas
function valid(x, y) {
return x >= 0 && x <= width - 1 && y >= 0 && y <= height - 1;
}
[[the problem/what should be happening](https://i.stack.imgur.com/XOwYB.png)](https://i.stack.imgur.com/LNLeV.png)```
由于代码块错误,我无法运行您发布的代码。以下源代码将运行,但不是原作者预期的方式。当我试图跟随他的视频演示时,我的个人副本也发生了完全相同的情况。我能想到的唯一可能的解释是他使用了不同的编辑器或浏览器。我在 Mac 上的 Chrome 浏览器中使用了 p5.js Web 编辑器。当按下一个键时,背景会变成红色,而不是像他想要的那样,形状的内部会变成红色。它确实可以在他的设置中正常工作,但在我的设置中不能正常工作,显然也不能在你的设置中正常工作。抱歉,我不知道如何彻底修复它。
let imageData;
function setup() {
createCanvas(1000, 1000);
pixelDensity(1); // The fix
}
function draw() {
if (mouseIsPressed) {
line(floor(pmouseX), floor(pmouseY), floor(mouseX), floor(mouseY));
}
}
function keyPressed() {
imageData = drawingContext.getImageData(0, 0, 1000, 1000);
floodFill(floor(mouseX), floor(mouseY));
drawingContext.putImageData(imageData, 0, 0);
}
function floodFill(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]);
}
}
//set color of pixel
function setPixel(x, y) {
let pixels = imageData.data;
let i = (y * width + x) * 4;
pixels[i] = 255;
pixels[i + 1] = 0;
pixels[i + 2] = 0;
pixels[i + 3] = 255;
}
//make sure it has color
function isPixel(x, y) {
let pixels = imageData.data;
let i = (y * width + x) * 4;
return pixels[i + 3] > 0;
}
//make sure it is in bounds of canvas
function valid(x, y) {
return x >= 0 && x <= width - 1 && y >= 0 && y <= height - 1;
}
附录:
最近在另一个论坛上讨论过。将“pixelDensity(1)”添加到 setup() 可以修复此问题。根据文档,这会关闭 PixelDensity()。