【发布时间】:2018-08-19 23:34:29
【问题描述】:
我一直在尝试使用初始 mouseX 和 mouseY 值创建填充函数。在尝试使用 4 路递归方法并失败后,我发现一篇文章建议使用数组来存储 4 路值并使用 .push() 函数将它们排队。当数组有值时,该函数将使用 .pop() 函数为 x 和 y 设置新值,然后依次测试并更改为所需的颜色。
在尝试使用这种方法进行洪水填充后,我仍然在努力获得任何与速度有关的性能。我试图包含一个额外的检查历史记录函数来存储访问像素的历史记录,并防止任何重复的 x,y 坐标被推回队列中。但是(当使用控制台记录“找到匹配”时)该函数似乎没有找到任何重复。
我非常感谢有关如何改进我迄今为止编写的代码的任何指导。或者也许是对实施起来并不复杂的不同方法的建议。我很少使用 Stack Overflow,也希望获得有关如何格式化问题和代码以供将来参考的指导。感谢您的任何时间。
使用我包含的sketch.js,您可以看到填充功能在非常小的物体(第一个初始正方形)上是可以接受的,但随着尺寸的增加,性能会停止。
index.html
<!DOCTYPE html>
<html>
<head>
<script src="p5.min.js"></script>
<script src="sketch.js"></script>
<style> body {padding: 0; margin: 0;} </style>
</head>
<body>
</body>
</html>
sketch.js
var colorNew = [0,255,0,255];
function setup()
{
createCanvas(500,500);
squares();
}
function squares(){
background(255);
noFill();
stroke(0);
rect(125,125,10,10);
rect(125,125,20,20);
rect(125,125,30,30);
rect(125,125,40,40);
rect(125,125,50,50);
updatePixels();
}
function getPixData(xPos,yPos){
colorOld = get(xPos,yPos);
};
function checkValue(xPos,yPos,oldColor){
var currentPix
currentPix = get(xPos,yPos);
if(currentPix[0] == oldColor[0] && currentPix[1] == oldColor[1] && currentPix[2] == oldColor[2] && currentPix[3] == oldColor[3]){
return true;
}
};
function checkHistory(x1,y1,historyArray){
for (var i = 0 ; i < historyArray.length; i+=2){
if(x1 == historyArray[i] && y1 == historyArray[i+1]){
console.log("match found");
return false;
}else {
console.log(historyArray.length)
return true;
}
}
};
function floodFill (xPos,yPos){
getPixData(mouseX,mouseY);
var stack = [];
var historyList = [];
stack.push(xPos,yPos);
historyList.push(xPos,yPos);
console.log(stack);
while(stack.length> 0){
var yPos1 = stack.pop();
var xPos1 = stack.pop();
set(xPos1,yPos1,colorNew);
updatePixels();
if(xPos1+1 <= width && xPos1+1 > 0 ){
if(checkValue(xPos1+1,yPos1,colorOld) && checkHistory(xPos1+1,yPos1,historyList)){
stack.push(xPos1+1,yPos1);
historyList.push(xPos1+1,yPos1);
console.log("right checked")
}
}
if(xPos1+1 <= width && xPos1+1 > 0 ){
if(checkValue(xPos1-1,yPos1,colorOld) && checkHistory(xPos1-1,yPos1,historyList)){
stack.push(xPos1-1,yPos1);
historyList.push(xPos1-1,yPos1);
console.log("left checked");
}
}
if(yPos1+1 <= height && yPos1+1 > 0 ){
if(checkValue(xPos1,yPos1+1,colorOld) && checkHistory(xPos1,yPos1+1,historyList)){
stack.push(xPos1,yPos1+1);
historyList.push(xPos1,yPos1+1);
console.log("above checked");
}
}
if(yPos1-1 <= height && yPos1-1 > 0 ){
if(checkValue(xPos1,yPos1-1,colorOld) && checkHistory(xPos1,yPos1-1,historyList)){
stack.push(xPos1,yPos1-1);
historyList.push(xPos1,yPos1-1);
console.log("below checked");
}
}
}
console.log(historyList);
}
function draw()
{
if(mouseIsPressed){
floodFill(mouseX,mouseY)
}
}
【问题讨论】:
标签: javascript stack p5.js flood-fill