# Bayer ordered dithering

One image of Saturn is printed in navy and apricot. A larger repeating threshold matrix creates more apparent shades by varying the density of the two inks.

## Try it

Inspect the rings and the gradient strip at 1×1. Switch to 4×4 and then 8×8 to compare the dot patterns in the shadows.

## Interaction details

Each threshold is its matrix rank plus 0.5 divided by the number of cells. A 4×4 tile yields 17 coverage levels and an 8×8 tile yields 65. Reduced motion renders the new print immediately.

## Platform controls

- iOS · Tap a matrix size and compare the rings and gradient strips in the two proofs.
- Android · Tap a matrix size and compare the rings and gradient strips in the two proofs.
- PC · Tab to a matrix button and press Enter or Space.

## Where to use it

Render intermediate tones in two-colour pixel art or a two-ink print proof.

## Implementation prompt

> Keep the source shading fixed while switching between 1×1, 2×2, 4×4 and 8×8 Bayer matrices. Choose one of two inks per pixel and show the available coverage levels.

## Sources and credits

[ImageMagick · Ordered dithering](<https://usage.imagemagick.org/quantize/#ordered-dither>)

## 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{font:15px/1.4 system-ui,sans-serif;color:#253346;background:#f4eee0;color-scheme:light}body{margin:0;min-height:100svh;padding:clamp(12px,3vw,26px);display:grid;align-content:center}main{width:min(100%,720px);margin:auto}header,.head,.controls,.key,.readout{display:flex;align-items:center;flex-wrap:wrap;gap:8px}header,.head,.controls{justify-content:space-between}h1{font:600 clamp(21px,4.6vw,34px)/1.2 Georgia,serif;margin:0;letter-spacing:-.04em}header{border-bottom:2px solid #263751;padding-bottom:10px;margin-bottom:12px}header span,.head,.key,.readout{font-size:clamp(10px,2vw,13px);font-weight:650}.proofs{display:grid;grid-template-columns:1fr 1fr;gap:8px}.proof{min-width:0;background:#22324a;color:#fff5d7;border-radius:9px;overflow:hidden;padding:0 5px 5px}.head{padding:7px 5px}.head small{font:600 10px ui-monospace,monospace;color:#f0bda8}.proof canvas{width:100%;display:block;aspect-ratio:124/76;image-rendering:pixelated;border-radius:3px}.ink{width:9px;height:9px;background:#243650;border-radius:50%;display:inline-block;margin-right:2px}.ink.light{background:#f5d29a;border:1px solid #745c42}.controls{margin-top:12px;background:#fffbf2;border:1px solid #c3bbac;border-radius:9px;padding:8px 12px}.switches{display:flex;gap:5px;flex-wrap:wrap}button{border:1px solid #a6a08f;border-radius:5px;color:#29384b;background:transparent;font:650 13px/1 ui-monospace,monospace;padding:9px 11px;cursor:pointer;min-height:35px}button[aria-pressed="true"]{background:#273a50;color:#fff2d2;border-color:#273a50}button:focus-visible{outline:3px solid #c05239;outline-offset:2px}.readout{gap:7px}.readout canvas{width:29px;height:29px;image-rendering:pixelated;border:1px solid #536273}.key{justify-content:space-between;gap:5px;margin-top:7px}.key>span:first-child{display:flex;align-items:center;gap:3px}.hint{margin:7px 0 0;font-size:clamp(11px,1.8vw,13px);color:#4b5358}
@media(max-width:480px){.proofs{gap:5px}.proof{padding:0 3px 3px}.head{padding:5px 2px}.controls{padding:6px}.switches{gap:3px}button{padding:7px}.readout canvas{width:20px;height:20px}header{margin-bottom:8px}.head small{display:none}}
</style></head>
<body><main><header><h1 data-t="title"></h1><span data-t="method"></span></header>
<div class="proofs"><section class="proof"><div class="head"><span data-t="source"></span></div><canvas id="source" width="124" height="76" role="img"></canvas></section><section class="proof"><div class="head"><span data-t="result"></span></div><canvas id="result" width="124" height="76" role="img"></canvas></section></div>
<div class="key"><span><i class="ink"></i><i class="ink light"></i><span data-t="palette"></span></span><span data-t="ramp"></span></div>
<div class="controls"><div class="switches" role="group" id="switches"><button type="button" data-n="1" id="matrix1">1×1</button><button type="button" data-n="2" id="matrix2">2×2</button><button type="button" data-n="4" id="matrix4">4×4</button><button type="button" data-n="8" id="matrix8">8×8</button></div><div class="readout"><canvas id="tile" width="8" height="8" aria-hidden="true"></canvas><output id="levels" aria-live="polite"></output></div></div>
<p class="hint" data-t="hint"></p></main><script>
const words={
 ko:{title:'두 잉크로 찍은 토성',method:'바이어 순서 디더링',source:'원본 명암',result:'두 잉크 인쇄본',palette:'남색 · 살구색',ramp:'아래 띠 · 같은 명암 경사',matrix:'문턱값 행렬',levels:'농도 %단계',hint:'행렬 크기를 바꾸며 고리의 그림자와 아래 명암 띠를 비교해 보세요.'},
 en:{title:'Saturn in two inks',method:'Bayer ordered dither',source:'Tonal original',result:'Two-ink print',palette:'Navy · apricot',ramp:'Lower strip · same gradient',matrix:'Threshold matrix',levels:'% coverage levels',hint:'Switch matrix sizes. Compare the shadows on the rings and the gradient strips below.'},
 es:{title:'Saturno en dos tintas',method:'Tramado Bayer',source:'Original tonal',result:'Impresión a dos tintas',palette:'Azul marino · albaricoque',ramp:'Franja inferior · mismo degradado',matrix:'Matriz de umbrales',levels:'% densidades',hint:'Cambia el tamaño de la matriz y compara las sombras de los anillos y las franjas inferiores.'},
 'zh-Hans':{title:'双色油墨印土星',method:'拜耳有序抖动',source:'原始明暗',result:'双色印样',palette:'藏青 · 杏黄',ramp:'下方色带 · 同一渐变',matrix:'阈值矩阵',levels:'% 级密度',hint:'切换矩阵大小，比较行星环的阴影与下方的渐变条。'}
};
const params=new URLSearchParams(location.search),root=document.documentElement;
const requested=params.get('lang')||root.lang,lang=Object.hasOwn(words,requested)?requested:'ko',msg=words[lang];root.lang=lang;document.title=msg.title;
document.querySelectorAll('[data-t]').forEach(el=>el.textContent=msg[el.dataset.t]);
const source=document.getElementById('source'),result=document.getElementById('result'),tile=document.getElementById('tile'),levels=document.getElementById('levels');
source.setAttribute('aria-label',msg.source);result.setAttribute('aria-label',msg.result);document.getElementById('switches').setAttribute('aria-label',msg.matrix);
const width=source.width,height=source.height,shades=new Float32Array(width*height);
const dark=[36,54,80],light=[245,210,154],clamp=v=>Math.min(1,Math.max(0,v));
// Compute one source field, shared by every plate. The bottom band is a linear reference ramp.
for(let y=0;y<height;y++)for(let x=0;x<width;x++){
  const dx=x-62,dy=y-32,rx=dx*.964-dy*.267,ry=dx*.267+dy*.964;
  const ring=Math.hypot(rx/52,ry/11.8),radius=Math.hypot(dx/22,dy/22);
  let value=.10+.24*(1-y/height)+.09*x/width;
  const ringValue=.62+.24*Math.sin(ring*47)+.08*rx/52;
  if(ring>=.68&&ring<=1)value=ringValue;
  if(radius<=1){
    const normal=Math.sqrt(Math.max(0,1-radius*radius));
    value=.43+.45*(-dx/22*.68-dy/22*.5+normal*.52)+.085*Math.sin((dy+dx*.17)*.61);
  }
  if(ry>0&&ring>=.68&&ring<=1)value=ringValue;
  if(y>=67)value=x/(width-1);
  if(y===65||y===66)value=0;
  shades[y*width+x]=clamp(value);
}
const stars=[[10,15],[25,31],[102,9],[116,41],[86,50],[39,6],[16,53]];
for(const [x,y] of stars)shades[y*width+x]=.98;
function makeMatrix(size){
  let matrix=[0];
  for(let side=1;side<size;side*=2){
    const next=[],offsets=[0,2,3,1];
    for(let y=0;y<side*2;y++)for(let x=0;x<side*2;x++)next.push(4*matrix[(y%side)*side+x%side]+offsets[Math.floor(y/side)*2+Math.floor(x/side)]);
    matrix=next;
  }
  return matrix;
}
function plate(size){
  const frame=new ImageData(width,height),matrix=size?makeMatrix(size):null;
  for(let i=0;i<shades.length;i++){
    const x=i%width,y=Math.floor(i/width);
    const shade=matrix?Number(shades[i]>=(matrix[(y%size)*size+(x%size)]+.5)/(size*size)):shades[i];
    for(let ch=0;ch<3;ch++)frame.data[i*4+ch]=Math.round(dark[ch]+(light[ch]-dark[ch])*shade);
    frame.data[i*4+3]=255;
  }
  return frame;
}
source.getContext('2d').putImageData(plate(0),0,0);
const print=result.getContext('2d'),model=matchMedia('(prefers-reduced-motion: reduce)');
let size=0,frameId=0,finalFrame;
function reduced(){return params.get('reduce')==='1'||root.classList.contains('motion-reduced')||model.matches}
function finish(){cancelAnimationFrame(frameId);if(finalFrame)print.putImageData(finalFrame,0,0);result.dataset.complete='true'}
function show(n){
  if(n===size)return;
  const animate=size>0&&!reduced();size=n;cancelAnimationFrame(frameId);finalFrame=plate(n);
  document.querySelectorAll('[data-n]').forEach(b=>b.setAttribute('aria-pressed',String(Number(b.dataset.n)===n)));
  levels.textContent=msg.levels.replace('%',String(n*n+1)); result.dataset.size=String(n);
  tile.width=tile.height=n;const tc=tile.getContext('2d'),matrix=makeMatrix(n);
  matrix.forEach((v,i)=>{const pct=(v+.5)/(n*n);tc.fillStyle='rgb('+dark.map((c,k)=>Math.round(c+(light[k]-c)*pct)).join(',')+')';tc.fillRect(i%n,Math.floor(i/n),1,1)});
  if(!animate){finish();return}
  result.dataset.complete='false';const start=performance.now();
  function reveal(now){const p=Math.min(1,(now-start)/660);if(p>=1){finish();return}const edge=Math.max(1,Math.round(p*width));print.putImageData(finalFrame,0,0,0,0,edge,height);frameId=requestAnimationFrame(reveal)}
  frameId=requestAnimationFrame(reveal);
}
model.addEventListener('change',()=>{if(reduced())finish()});
document.querySelectorAll('[data-n]').forEach(b=>b.addEventListener('click',()=>show(Number(b.dataset.n))));show(1);
</script></body></html>
```
