我改编了我在这里找到的解决方案:http: //www.williammalone.com/articles/html5-canvas-javascript-paint-bucket-tool/
它像扫描线一样工作,并创建节点以在其路径被阻塞时将扫描返回到不同的方向,这就是“pixelStack”。
一般来说,我见过的所有好的解决方案都涉及创建一堆阻塞的位置以返回,填充算法的路径基本上是从这些位置分叉的。
function fill(startX,startY,fcol,bcol,vram){
// This function adapted from code at:
// http://www.williammalone.com/articles/html5-canvas-javascript-paint-bucket-tool/
// and https://github.com/williammalone/HTML5-Paint-Bucket-Tool/blob/master/html5-canvas-paint-bucket.js
// Copyright 2010 William Malone (www.williammalone.com)
//
// Thanks William, yours works better than mine did. :)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this fill function except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var pixelStack = [[startX, startY]];
var startColor = point(startX,startY,vram);
while(pixelStack.length)
{
var newPos, x, y, pixelPos, reachLeft, reachRight;
newPos = pixelStack.pop();
x = newPos[0];
y = newPos[1];
pixelPos = (y*canvasWidth + x);
while(y-- >= 25 && matchStartColor(pixelPos,startColor,vram))
{
pixelPos -= canvasWidth;
}
pixelPos += canvasWidth;
++y;
reachLeft = false;
reachRight = false;
while(y++ < canvasHeight-1 && matchStartColor(pixelPos,startColor,vram))
{
colorPixel(pixelPos,fcol,vram);
if(x > 0)
{
if(matchStartColor(pixelPos - 1,startColor,vram))
{
if(!reachLeft){
pixelStack.push([x - 1, y]);
reachLeft = true;
}
}
else if(reachLeft)
{
reachLeft = false;
}
}
if(x < canvasWidth-1)
{
if(matchStartColor(pixelPos + 1,startColor,vram))
{
if(!reachRight)
{
pixelStack.push([x + 1, y]);
reachRight = true;
}
}
else if(reachRight)
{
reachRight = false;
}
}
pixelPos += canvasWidth;
}
}
function matchStartColor(pixelPos,startColor,vram)
{
return (vram[pixelPos]==startColor);
}
function colorPixel(pixelPos,col,vram)
{
pset(pixelPos%320,Math.floor(pixelPos/320),col,vram)
}
}