GENERATIVE / 211

Voronoi regions

いちばん近い点で区切る
各位置を最も近い点の領域に分けます。見本は5px単位の近似描画です。

見本の中を操作して変化を試してください。

ラボで詳しく試す ↗

ひとつ試すなら

点の数と配置を変え、境界の位置を比べてください。

こんなときに

細胞状の模様、領域の分割。

仕組みと使い方

点の数と配置を変え、境界の位置を比べてください。

ボロノイ領域細胞生成
実装コードを見る
<!doctype html><html lang="ja"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{margin:0;min-height:330px}.sample{width:100%;height:100%;min-height:330px;padding:12px!important;display:flex!important;flex-direction:column;justify-content:center;align-items:center;gap:8px!important;background:#f0efeb;color:#232323;font-family:Arial,Meiryo,sans-serif;overflow:hidden;box-sizing:border-box}.sample *{box-sizing:border-box}.lab-scene{width:100%;max-width:430px;height:140px;position:relative;overflow:hidden;border-bottom:1px solid #ccc}.lab-scene:has(canvas){max-width:320px;height:auto;aspect-ratio:16/9;flex-shrink:0}.lab-canvas{display:block;width:100%;height:100%!important;outline-offset:-3px}.lab-canvas:focus-visible{outline:2px solid #222}.lab-controls{width:100%;max-width:390px;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 14px}.lab-controls label{display:grid;grid-template-columns:1fr auto;gap:2px;font-size:11px;min-width:0}.lab-controls input{grid-column:1/-1;width:100%;min-width:0;margin:0;accent-color:#333;height:30px}.lab-controls output{font-variant-numeric:tabular-nums}.lab-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap;justify-content:center}.sample .lab-actions button{color:inherit;font:11px Arial,Meiryo,sans-serif;border:1px solid #aaa;border-radius:99px;background:transparent;min-height:44px;padding:8px 12px;cursor:pointer}.lab-status{font-size:10px;line-height:1.4;min-height:14px;margin:0;text-align:center}.lab-note{font-size:9px;line-height:1.3;color:#666;margin:0;text-align:center}.lab-actions button:focus-visible{outline:2px solid #222;outline-offset:2px}@media(prefers-reduced-motion:reduce){.sample *{animation-play-state:paused!important;transition:none!important}}</style><div class="sample"><div class="lab-scene"><canvas class="lab-canvas" tabindex="0" role="img" aria-label="いちばん近い点で区切る。矢印キーでも位置を変えられます。" style="touch-action:pan-y"></canvas></div><div class="lab-controls"><label>基準点の数<output>10</output><input aria-label="基準点の数" type="range" min="3" max="20" step="1" value="10" data-key="count"></label><label>配置<output>2</output><input aria-label="配置" type="range" min="0" max="10" step="0.1" value="2" data-key="seed"></label></div><div class="lab-actions"><button type="button" data-play>停止</button><button type="button" data-reset>最初から</button></div><p class="lab-status"></p></div><script>const lab=(function runCanvasLab(root,cfg,draw){
 const canvas=root.querySelector('canvas'),ctx=canvas.getContext('2d'),status=root.querySelector('.lab-status'),play=root.querySelector('[data-play]'),reset=root.querySelector('[data-reset]'),abort=new AbortController(),mq=matchMedia('(prefers-reduced-motion:reduce)');
 const values=Object.fromEntries(cfg.controls.map(c=>[c.key,c.value]));let state={},time=0,frame=0,last=0,allowed=!mq.matches,userPaused=false,destroyed=false,visible=true;
 const pointer={x:160,y:90,down:false,active:false,dx:0,dy:0};let event='init';
 const on=(el,type,fn,opts={})=>el.addEventListener(type,fn,{...opts,signal:abort.signal});
 const circle=(x,y,r,fill='#292929')=>{ctx.beginPath();ctx.arc(x,y,Math.max(.1,r),0,Math.PI*2);ctx.fillStyle=fill;ctx.fill()};
 const line=(x,y,a,b,color='#aaa',width=1)=>{ctx.beginPath();ctx.strokeStyle=color;ctx.lineWidth=width;ctx.moveTo(x,y);ctx.lineTo(a,b);ctx.stroke()};
 const text=(str,x,y,size=12,color='#333',align='center')=>{ctx.fillStyle=color;ctx.font=`${size>25?'700':'400'} ${size}px Arial, sans-serif`;ctx.textAlign=align;ctx.fillText(str,x,y)};
 function render(dt=0){if(destroyed||!ctx)return;ctx.setTransform(canvas.width/320,0,0,canvas.height/180,0,0);ctx.clearRect(0,0,320,180);ctx.save();draw({ctx,w:320,h:180,time,dt,values,state,pointer,event,kind:cfg.kind,circle,line,text,status:s=>{status.textContent=s}});ctx.restore();event='';}
 function tick(now){frame=0;if(!running())return;const dt=Math.min((now-(last||now))/1000,.033);last=now;time+=dt;render(dt);frame=requestAnimationFrame(tick)}
 function running(){return !destroyed&&allowed&&!userPaused&&visible&&!document.hidden&&cfg.animated!==false}
 function sync(){cancelAnimationFrame(frame);frame=0;last=0;if(running())frame=requestAnimationFrame(tick);play.textContent=running()?'停止':'再生';play.setAttribute('aria-pressed',String(userPaused));}
 function resize(){const dpr=Math.min(devicePixelRatio||1,2);canvas.width=Math.round(640*dpr);canvas.height=Math.round(360*dpr);render()}
 on(play,'click',()=>{userPaused=running();if(!userPaused)allowed=true;sync();render()});
 on(reset,'click',()=>{state={};time=0;event='reset';pointer.down=false;render();sync()});
 for(const input of root.querySelectorAll('[data-key]')){on(input,'input',()=>{values[input.dataset.key]=Number(input.value);input.closest('label').querySelector('output').textContent=input.value;event='input';render()})}
 function position(e){const b=canvas.getBoundingClientRect(),x=(e.clientX-b.left)/b.width*320,y=(e.clientY-b.top)/b.height*180;pointer.dx=x-pointer.x;pointer.dy=y-pointer.y;pointer.x=Math.max(0,Math.min(320,x));pointer.y=Math.max(0,Math.min(180,y));pointer.active=true;}
 on(canvas,'pointerdown',e=>{position(e);pointer.down=true;event='down';canvas.setPointerCapture(e.pointerId);render()});
 on(canvas,'pointermove',e=>{position(e);event='move';render()});
 on(canvas,'pointerup',e=>{position(e);pointer.down=false;event='up';render()});
 on(canvas,'pointercancel',()=>{pointer.down=false;event='cancel';render()});
 on(canvas,'pointerleave',()=>{pointer.active=false;if(!pointer.down){event='leave';render()}});
 on(canvas,'keydown',e=>{const keys={ArrowLeft:[-12,0],ArrowRight:[12,0],ArrowUp:[0,-12],ArrowDown:[0,12]};if(keys[e.key]){e.preventDefault();pointer.active=true;pointer.x=Math.max(0,Math.min(320,pointer.x+keys[e.key][0]));pointer.y=Math.max(0,Math.min(180,pointer.y+keys[e.key][1]));event='keyboard';render()}if(e.key===' '||e.key==='Enter'){e.preventDefault();pointer.down=!pointer.down;pointer.active=true;event=pointer.down?'down':'up';render()}});
 on(document,'visibilitychange',sync);on(mq,'change',()=>{allowed=!mq.matches;sync();render()});
 const observer=new IntersectionObserver(entries=>{visible=entries[0].isIntersecting;sync()});observer.observe(canvas);resize();sync();
 if(cfg.animated===false)play.hidden=true;
 return {setAuto(on){allowed=on&&!mq.matches;sync()},destroy(){destroyed=true;cancelAnimationFrame(frame);abort.abort();observer.disconnect();state={}}};
})(document,{"kind":"generative-voronoi","controls":[{"key":"count","label":"基準点の数","min":3,"max":20,"value":10,"step":1},{"key":"seed","label":"配置","min":0,"max":10,"value":2,"step":0.1}],"animated":false},function generative({ctx,time,values:v,state:s,kind,circle,line,text,status}){
 const k=kind.split('-')[1];
 if(k==='flow'){for(let y=12;y<180;y+=12)for(let x=10;x<320;x+=12){const a=Math.sin(x/v.scale+time*.25)*Math.cos(y/v.scale-time*.15)*v.turn;line(x,y,x+Math.cos(a)*9,y+Math.sin(a)*9,'#555')}}
 else if(k==='fractal'){function branch(x,y,len,a,depth){if(depth<=0)return;const nx=x+Math.cos(a)*len,ny=y+Math.sin(a)*len;line(x,y,nx,ny,depth>3?'#222':'#888',Math.max(.5,depth*.4));branch(nx,ny,len*.69,a-v.angle,depth-1);branch(nx,ny,len*.69,a+v.angle,depth-1)}branch(160,175,55,-Math.PI/2,v.depth);}
 else if(k==='voronoi'){const points=Array.from({length:v.count},(_,i)=>({x:160+Math.sin(i*5.4+v.seed)*145,y:90+Math.cos(i*3.2+v.seed)*78}));for(let y=0;y<180;y+=5)for(let x=0;x<320;x+=5){let min=Infinity,which=0;points.forEach((p,i)=>{const d=(x-p.x)**2+(y-p.y)**2;if(d<min){min=d;which=i}});const shade=80+which*19%150;ctx.fillStyle=`rgb(${shade},${shade},${shade})`;ctx.fillRect(x,y,5,5)}points.forEach(p=>circle(p.x,p.y,2,'#fff'));}
 else{const cols=64,rows=36;let row=Array(cols).fill(0);row[32]=1;for(let y=0;y<rows;y++){for(let x=0;x<cols;x++)if(row[x]){ctx.fillStyle='#333';ctx.fillRect(x*5,y*5,5,5)}row=row.map((_,x)=>(v.rule>>((row[(x+cols-1)%cols]<<2)|(row[x]<<1)|row[(x+1)%cols]))&1)}text('rule '+v.rule,275,17,10,'#888');}status(k==='flow'?'各点の向きを、同じ数式で決める':'規則を少し変えて、全体の変化を見る');
});addEventListener('pagehide',()=>lab.destroy(),{once:true});</script></html>