// Color-region detection used by the paint bucket and magic wand. import { createCanvas } from '../core/util.js'; /** * Compute a region mask of pixels similar to the seed pixel. * @returns {Uint8Array|null} 255 = in region; null if seed is outside. */ export function regionMask(imageData, sx, sy, tolerance, contiguous = true) { const { width: w, height: h, data } = imageData; sx = Math.floor(sx); sy = Math.floor(sy); if (sx < 0 || sy < 0 || sx >= w || sy >= h) return null; const si = (sy * w + sx) * 4; const r0 = data[si], g0 = data[si + 1], b0 = data[si + 2], a0 = data[si + 3]; const tol = tolerance; const out = new Uint8Array(w * h); const match = (p) => { const i = p * 4; const a = data[i + 3]; // Fully transparent pixels match each other regardless of their (meaningless) RGB. if (a0 === 0 && a === 0) return true; return Math.abs(data[i] - r0) <= tol && Math.abs(data[i + 1] - g0) <= tol && Math.abs(data[i + 2] - b0) <= tol && Math.abs(a - a0) <= tol; }; if (!contiguous) { for (let p = 0; p < w * h; p++) if (match(p)) out[p] = 255; return out; } // Scanline flood fill. const stack = [sx, sy]; while (stack.length) { const y = stack.pop(); let x = stack.pop(); let p = y * w + x; while (x > 0 && !out[p - 1] && match(p - 1)) { x--; p--; } let spanUp = false, spanDown = false; for (; x < w; x++, p++) { if (out[p] || !match(p)) break; out[p] = 255; if (y > 0) { const up = p - w; if (!out[up] && match(up)) { if (!spanUp) { stack.push(x, y - 1); spanUp = true; } } else spanUp = false; } if (y < h - 1) { const dn = p + w; if (!out[dn] && match(dn)) { if (!spanDown) { stack.push(x, y + 1); spanDown = true; } } else spanDown = false; } } } return out; } /** Turn a 0/255 region into an alpha mask canvas. Optional 1px antialias softening. */ export function regionToCanvas(region, w, h, antialias = false) { const c = createCanvas(w, h); const ctx = c.getContext('2d'); const id = ctx.createImageData(w, h); const d = id.data; for (let p = 0; p < region.length; p++) d[p * 4 + 3] = region[p]; if (antialias) { // Soften edge pixels: average with 4-neighbours where the region boundary is. const src = region; for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { const p = y * w + x; const v = src[p]; const l = x > 0 ? src[p - 1] : v, r = x < w - 1 ? src[p + 1] : v; const u = y > 0 ? src[p - w] : v, dn = y < h - 1 ? src[p + w] : v; if (l !== v || r !== v || u !== v || dn !== v) d[p * 4 + 3] = (v * 4 + l + r + u + dn) / 8; } } } ctx.putImageData(id, 0, 0); return c; } /** Bounding rect of a region, or null. */ export function regionBounds(region, w, h) { let minX = w, minY = h, maxX = -1, maxY = -1; for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { if (region[y * w + x]) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; } } } return maxX < 0 ? null : { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 }; }