Nadesłany przez Tomasz Lubiński, 22 lutego 2012 21:31
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.Pobierz pełne rozwiązanie.
Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
flood_fill.js:
//Flood fill
//(c) 2011 by Tomasz Lubinski
//www.algorytm.org
/* Data of the image */
var imageData;
var width, height;
var R, G, B;
var RtoFill, GtoFill, BtoFill;
/* Flood fill */
function floodFill(x, y, type)
{
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
RtoFill = imageData.data[(y*width+x)*4+0];
GtoFill = imageData.data[(y*width+x)*4+1];
BtoFill = imageData.data[(y*width+x)*4+2];
// do not fill if already filled with this color
if (RtoFill == R && GtoFill == G && BtoFill == B)
return;
if (type == 4)
{
//call flood fill with four directions
floodFill4(x, y);
}
else
{
//call flood fill with eight directions
floodFill8(x, y);
}
// copy the image data back onto the canvas
ctx.putImageData(imageData, 0, 0);
}
/* Flood fill algorithm with 4 directions */
function floodFill4(x, y)
{
if (x<0 || x>=width || y<0 || y>=height)
{
//outside image
return;
}
if (imageData.data[(y*width+x)*4+0] != RtoFill ||
imageData.data[(y*width+x)*4+1] != GtoFill ||
imageData.data[(y*width+x)*4+2] != BtoFill)
{
//not color to fill
return;
}
//fill with color
imageData.data[(y*width+x)*4+0] = R;
imageData.data[(y*width+x)*4+1] = G;
imageData.data[(y*width+x)*4+2] = B;
//call in four new directions
floodFill4(x-1, y );
floodFill4(x+1, y );
floodFill4(x , y-1);
floodFill4(x , y+1);
}
/* Flood fill algorithm with 8 directions */
function floodFill8(x, y)
{
if (x<0 || x>=width || y<0 || y>=height)
{
//outside image
return;
}
if (imageData.data[(y*width+x)*4+0] != RtoFill ||
imageData.data[(y*width+x)*4+1] != GtoFill ||
imageData.data[(y*width+x)*4+2] != BtoFill)
{
//not color to fill
return;
}
//fill with color
imageData.data[(y*width+x)*4+0] = R;
imageData.data[(y*width+x)*4+1] = G;
imageData.data[(y*width+x)*4+2] = B;
//call in eight new directions
floodFill8(x-1, y );
floodFill8(x-1, y+1);
floodFill8(x , y+1);
floodFill8(x+1, y+1);
floodFill8(x+1, y );
floodFill8(x+1, y-1);
floodFill8(x , y-1);
floodFill8(x-1, y-1);
}
/* load image pointed by param_file to canvas */
function loadImage(imgSrc)
{
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// add file:// if user specified local path
if (imgSrc.indexOf("//") == -1 && imgSrc.indexOf(".") != 0)
{
imgSrc = "file:///" + imgSrc;
}
// load file into canvas
var img = new Image();
img.onload = function(){
width = img.width;
height = img.height;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img,0,0);
// get image data
try
{
imageData = ctx.getImageData(0, 0, width, height);
} catch(e)
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
imageData = ctx.getImageData(0, 0, width, height);
}
}
img.src = imgSrc;
}

