Skip to content

Instantly share code, notes, and snippets.

@FlyInk13
Last active February 28, 2018 15:54
Show Gist options
  • Save FlyInk13/03e4a26613ab662408e5e0c53b500b31 to your computer and use it in GitHub Desktop.
Save FlyInk13/03e4a26613ab662408e5e0c53b500b31 to your computer and use it in GitHub Desktop.
floodFill.js canvas node.js
// rgb2lab + deltaE
// https://github.com/antimatter15/rgb-lab/blob/master/color.js
function deltaRGB(a, b) {
return deltaE(rgb2lab(a), rgb2lab(b));
}
function FloodFill(imageData, sx, sy, color, delta) {
var xy2i = (x, y) => (y * imageData.width + x) * 4;
var getColor = i => imageData.data.slice(i, i + 4);
var seen = {};
var cart = [[sx, sy]];
var startColor = getColor(xy2i(sx, sy));
var check = (x, y) => deltaRGB(getColor(xy2i(x, y)), startColor) <= delta;
while (cart.length) {
let [x, y] = cart.shift();
let i = xy2i(x, y);
if (seen[i] || !check(x, y)) continue;
imageData.data[i + 0] = color[0];
imageData.data[i + 1] = color[1];
imageData.data[i + 2] = color[2];
imageData.data[i + 3] = color[3];
seen[i] = 1;
if (x > 1) cart.push([x - 1, y]);
if (x < imageData.width) cart.push([x + 1, y]);
if (y > 1) cart.push([x, y - 1]);
if (y < imageData.height) cart.push([x, y + 1]);
}
cart = null;
seen = null;
return imageData;
}
// *** *** //
ctx.drawImage(img, 0, 0);
var imgData = ctx.getImageData(0, 0, img.width, img.height),
color = [0, 0, 0, 0];
ctx.putImageData(FloodFill(imgData, 0, 0, color, 30), 0, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment