# Connected flood fill

Ink spreads from a seed to matching cells above, below and beside it. Raising tolerance admits adjacent shades while the same colours across the water stay dry.

## Try it

On the west island, raise tolerance from 0 to 72. Its colour bands fill while the east island stays untouched.

## Interaction details

The 48 × 18 grid uses four-neighbour connectivity and compares each land cell with the seed shade. Reduced motion shows the completed region immediately.

## Platform controls

- iOS · Tap an island cell or an island button, then drag the tolerance slider.
- Android · Tap an island cell or an island button, then drag the tolerance slider.
- PC · Click a land cell, or focus the map, move with arrows and press Enter. Use the arrow keys on the tolerance slider.

## Where to use it

Colour one connected part of a pixel drawing or map.

## Implementation prompt

> Starting at a chosen pixel, fill similar land cells connected through four neighbours. Recompute from the same seed when tolerance changes and preserve land across water.

## Sources and credits

[GIMP · Bucket Fill](<https://docs.gimp.org/2.10/en/gimp-tool-bucket-fill.html>)

## Standalone HTML

Save the code below as an HTML file and open it in your browser. The example works offline.

```html
<!doctype html>
<html lang="en" data-motion-locales="inline">
<head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>두 섬의 연결 채우기</title>
<style>
*{box-sizing:border-box} :root{color-scheme:light;font:15px/1.4 system-ui,sans-serif;background:#f0ece1;color:#282f33}body{margin:0;min-height:100svh;display:grid;align-content:center;padding:clamp(10px,2.5vw,24px)}main{max-width:700px;width:100%;margin:auto}header,.tools,.controls,.caption,.readout{display:flex;align-items:center;gap:8px;flex-wrap:wrap}header,.readout,.caption{justify-content:space-between}h1{font-size:clamp(21px,4vw,33px);margin:0 0 8px;letter-spacing:-.055em}header small{font-weight:700;letter-spacing:.09em;color:#705e48}.sheet{padding:clamp(6px,2vw,12px);background:#272c34;border-radius:12px;color:#faf3da;box-shadow:0 2px 0 #bbb49f}.caption{font-size:11px;letter-spacing:.06em;margin:0 2px 5px}.caption b{color:#ffba72}canvas{width:100%;display:block;background:#254457;touch-action:manipulation;cursor:crosshair;aspect-ratio:2.6}.readout{margin:6px 2px 0;font-size:12px}.readout output{font-variant-numeric:tabular-nums;font-weight:700;color:#ffcb8c}.legend{display:flex;align-items:center;gap:5px}.legend i{width:9px;height:9px;background:#ef684e;transform:rotate(45deg)}.tools{margin-top:12px;justify-content:space-between}.tools label{font-weight:700;display:flex;align-items:center;gap:7px}.tools input{accent-color:#a85035;width:clamp(95px,19vw,160px)}button{font:inherit;font-weight:620;font-size:13px;background:#f9f5e9;color:#2c3438;border:1px solid #aa9d84;border-radius:6px;padding:7px 11px;min-height:39px;cursor:pointer}button.primary{color:#fff8e6;background:#274856;border-color:#274856}button:focus-visible,input:focus-visible,canvas:focus-visible{outline:3px solid #dc6942;outline-offset:2px}p{margin:9px 0 0;color:#554d42;font-size:13px}button:hover{filter:brightness(.93)}@media(max-width:450px){body{padding:10px}.tools{gap:9px}.controls{gap:5px}button{font-size:12px;padding:7px}}
</style></head>
<body><main><header><h1 data-t="title"></h1><small data-t="edition"></small></header>
<div class="sheet"><div class="caption"><span data-t="map"></span><b>48 × 18</b></div>
<canvas id="map" width="864" height="324" tabindex="0" role="button" aria-describedby="hint"></canvas>
<div class="readout"><span class="legend"><i></i><span data-t="seed"></span></span><output id="count" aria-live="polite"></output></div></div>
<div class="tools"><label><span data-t="tolerance"></span><input type="range" id="tolerance" min="0" max="72" step="1" value="0"><output id="value">0</output></label>
<div class="controls"><button type="button" id="west" class="primary" data-t="west"></button><button type="button" id="east" data-t="east"></button></div></div>
<p id="hint" data-t="hint"></p></main><script>
'use strict';
const copy={
ko:{title:'두 섬의 연결 채우기',edition:'격자 지도',map:'해안 인쇄 원판',seed:'시작 칸',count:'채운 칸',tolerance:'허용치',west:'서쪽 섬 칠하기',east:'동쪽 섬 칠하기',hint:'섬의 칸을 누르거나 두 섬 버튼을 사용하세요. 허용치를 높이면 닮은 색이 이어진 곳까지 채웁니다.',canvas:'지도. 화살표로 시작점을 옮기고 Enter로 칠하기'},
en:{title:'Flood-fill the two islands',edition:'GRID MAP',map:'COASTAL PRINT PLATE',seed:'Starting cell',count:'Cells filled',tolerance:'Tolerance',west:'Fill west island',east:'Fill east island',hint:'Pick a land cell or use the island buttons. Raise the tolerance to include connected cells with similar colours.',canvas:'Map. Move the starting point with the arrow keys and press Enter to fill'},
es:{title:'Relleno de dos islas',edition:'MAPA DE CUADRÍCULA',map:'PLANCHA COSTERA',seed:'Celda inicial',count:'Celdas rellenas',tolerance:'Tolerancia',west:'Rellenar isla oeste',east:'Rellenar isla este',hint:'Elige una celda de tierra o usa los botones. Sube la tolerancia para incluir celdas vecinas de color similar.',canvas:'Mapa. Mueve el punto inicial con las flechas y pulsa Intro para rellenar'},
'zh-Hans':{title:'两座岛的连通填充',edition:'网格地图',map:'海岸印版',seed:'起始格',count:'已填格数',tolerance:'容差',west:'填充西岛',east:'填充东岛',hint:'点按岛上的格子或使用下方按钮。提高容差可填充相连的近似色格子。',canvas:'地图。用方向键移动起点，按回车填充'}
};
const params=new URLSearchParams(location.search);
const requested=params.get('lang')||document.documentElement.lang;
const lang=Object.hasOwn(copy,requested)?requested:'ko',t=copy[lang];document.documentElement.lang=lang;document.title=t.title;
document.querySelectorAll('[data-t]').forEach(el=>el.textContent=t[el.dataset.t]);
const map=document.getElementById('map'),ctx=map.getContext('2d'),tolerance=document.getElementById('tolerance'),count=document.getElementById('count');
map.setAttribute('aria-label',t.canvas);
const columns=48,rows=18,unit=18,shades=['#f8d993','#eebd7c','#d99f6c'],levels=[0,28,58];
const land=new Int8Array(columns*rows).fill(-1),filled=new Uint8Array(land.length);
const islands=[{x:13,y:8.5,w:11,h:7.0,roll:.16},{x:36,y:8.8,w:8.4,h:6.8,roll:-.29}];
for(let y=0;y<rows;y++)for(let x=0;x<columns;x++){
  for(const s of islands){const a=(x-s.x)/s.w,b=(y-s.y)/s.h,theta=Math.atan2(b,a);
    const coast=Math.hypot(a,b)/(1+.12*Math.cos(3*theta+s.roll)+.10*Math.sin(2*theta-s.roll));
    if(coast<1){land[y*columns+x]=coast<.41?0:coast<.72?1:2;break;}
  }
}
const media=matchMedia('(prefers-reduced-motion: reduce)');
const reduced=()=>params.get('reduce')==='1'||document.documentElement.classList.contains('motion-reduced')||media.matches;
let seed=9*columns+13,cursor=seed,frame=0,waves=[],shown=0,total=0,side=0;
function draw(){
  for(let i=0;i<land.length;i++){const x=i%columns,y=Math.floor(i/columns);
    ctx.fillStyle=land[i]<0?['#264354','#29495a','#2d5060'][(x+2*y)%3]:filled[i]?['#e76c50','#d75c48','#cb4f40'][land[i]]:shades[land[i]];
    ctx.fillRect(x*unit,y*unit,unit,unit);
    if(land[i]>=0){ctx.fillStyle='#261d2414';ctx.fillRect(x*unit,y*unit,unit,1);ctx.fillRect(x*unit,y*unit,1,unit);}
    else if((x+3*y)%13===0){ctx.fillStyle='#75939a';ctx.fillRect(x*unit+5,y*unit+10,8,1);}
  }
  const cx=(cursor%columns+.5)*unit,cy=(Math.floor(cursor/columns)+.5)*unit;
  ctx.save();ctx.translate(cx,cy);ctx.rotate(Math.PI/4);ctx.fillStyle='#fff9db';ctx.strokeStyle='#3d3332';ctx.lineWidth=2;ctx.fillRect(-6,-6,12,12);ctx.strokeRect(-6,-6,12,12);ctx.restore();
  map.dataset.filled=String(total);map.dataset.side=String(side);map.dataset.seed=String(seed);map.dataset.complete=String(shown===waves.length);
}
function reveal(){
  for(const p of waves[shown++]){filled[p]=1;total++;}
}
function finish(){cancelAnimationFrame(frame);while(shown<waves.length)reveal();draw();count.textContent=t.count+' · '+total;}
function fill(index){
  if(land[index]<0)return;
  cancelAnimationFrame(frame);seed=cursor=index;side=(index%columns)<26?0:1;
  const seen=new Uint8Array(land.length);seen[index]=1;waves=[[index]];
  for(let n=0;n<waves.length;n++){
    const next=[];
    for(const p of waves[n]){
      const x=p%columns,y=Math.floor(p/columns);
      for(const [nx,ny] of [[x-1,y],[x+1,y],[x,y-1],[x,y+1]]){
        if(nx<0||nx>=columns||ny<0||ny>=rows)continue;
        const q=ny*columns+nx;if(seen[q]||land[q]<0||Math.abs(levels[land[q]]-levels[land[index]])>Number(tolerance.value))continue;
        seen[q]=1;next.push(q);
      }
    }
    if(next.length)waves.push(next);
  }
  filled.fill(0);shown=0;total=0;document.getElementById('value').textContent=tolerance.value;
  if(reduced()){finish();return;}
  const start=performance.now();count.textContent=t.count+' · …';
  function advance(time){const to=Math.min(waves.length,1+Math.floor((time-start)/34));while(shown<to)reveal();draw();if(shown<waves.length)frame=requestAnimationFrame(advance);else count.textContent=t.count+' · '+total;}
  advance(start);
}
map.addEventListener('click',e=>{const r=map.getBoundingClientRect();const x=Math.min(columns-1,Math.floor((e.clientX-r.left)/r.width*columns)),y=Math.min(rows-1,Math.floor((e.clientY-r.top)/r.height*rows));if(x>=0&&y>=0)fill(y*columns+x);});
map.addEventListener('keydown',e=>{if(e.key===' '||e.key==='Enter'){e.preventDefault();fill(cursor);return;}const dirs={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]};if(!Object.hasOwn(dirs,e.key))return;e.preventDefault();const [dx,dy]=dirs[e.key],x=cursor%columns+dx,y=Math.floor(cursor/columns)+dy;if(x>=0&&x<columns&&y>=0&&y<rows&&land[y*columns+x]>=0){cursor=y*columns+x;draw();}});
document.getElementById('west').onclick=()=>fill(9*columns+13);document.getElementById('east').onclick=()=>fill(9*columns+36);tolerance.oninput=()=>fill(seed);
media.addEventListener('change',()=>{if(reduced())finish();});new MutationObserver(()=>{if(reduced())finish();}).observe(document.documentElement,{attributes:true,attributeFilter:['class']});
fill(seed);finish();
</script></body></html>
```
