Dither Image
Dither shader for images: Bayer and blue-noise dithering to 2 to 4 inks, with a cursor loupe that sharpens, inverts or reveals.
- Dither
- Fashion / Media
- React only · 0 deps
- 1 file
Browser support · WebGL2 with WebGL1 fallback. Without WebGL a CSS halftone gradient is shown.
Install. One command, or copy the file.
$
npx shadcn@latest add https://freedesignmd.com/r/dither-image.json- Byte-identical to the preview
- No Tailwind or config needed
- SSR-safe · keyboard accessible
- Respects reduced motion & transparency
components/dither/dither-image.tsx
1/**2 * DitherImage, GPU ordered / blue-noise dithering of any image into a 2–43 * colour palette, with a cursor "loupe" that sharpens, inverts or reveals the4 * photo underneath.5 *6 * Props7 * - src?: string Image URL (loaded with crossOrigin="anonymous", cover-fitted).8 * - draw?: (ctx, w, h)=>void Procedural source drawn to an offscreen canvas (used when no src).9 * - palette?: string[] 2–4 hex colours, darkest → lightest. Default ink / paper.10 * - pixelSize?: number Dither cell size in CSS px. Default 3.11 * - algorithm?: "bayer2" | "bayer4" | "bayer8" | "blue-noise". Default "bayer8".12 * - contrast?: number 1 = neutral. Default 1.15.13 * - brightness?: number −0.5…0.5. Default 0.14 * - lens?: "sharpen" | "invert" | "reveal" | "none". Default "sharpen".15 * - lensRadius?: number CSS px. Default 140.16 * - children Overlay content (type, UI) rendered above the canvas.17 * CSS vars: --fd-dimg-radius, --fd-dimg-fallback.18 *19 * Browser support: WebGL2 with WebGL1 fallback. Without WebGL a CSS halftone20 * gradient is shown. Accessibility: pass `alt`, the canvas gets role="img".21 * Reduced motion: the loupe snaps instead of easing.22 *23 * Demo image: /img/people/p2.webp (placeholder portrait, included in the repo's24 * public/img/people, copy it next to your page or swap in your own).25 */26import { useEffect, useRef, useState } from "react";27import type { CSSProperties, MutableRefObject, ReactNode, RefObject } from "react";28 29/* ───────────────────────── tiny WebGL stage ───────────────────────── */30 31type GL = WebGLRenderingContext | WebGL2RenderingContext;32interface Stage {33 gl: GL;34 gl2: boolean;35 prog: WebGLProgram;36 u: Record<string, WebGLUniformLocation | null>;37 w: number;38 h: number;39 dpr: number;40 reduced: boolean;41}42interface StageHooks {43 setup?: (s: Stage) => void;44 /** Set uniforms; return true to keep animating. */45 frame: (s: Stage, time: number, dt: number) => boolean;46}47 48function createStage(canvas: HTMLCanvasElement, frag: string): Stage | null {49 const attrs: WebGLContextAttributes = { antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: "high-performance" };50 let gl: GL | null = canvas.getContext("webgl2", attrs) as WebGL2RenderingContext | null;51 const gl2 = !!gl;52 if (!gl) gl = (canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs)) as WebGLRenderingContext | null;53 if (!gl) return null;54 const head = gl2 ? "#version 300 es\n" : "";55 const vs = head + (gl2 ? "#define attribute in\n" : "") + "attribute vec2 aP;void main(){gl_Position=vec4(aP,0.,1.);}";56 const fs =57 head +58 "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n" +59 (gl2 ? "#define texture2D texture\n#define gl_FragColor fdOut\nout vec4 fdOut;\n" : "") +60 frag;61 const make = (type: number, src: string) => {62 const s = gl!.createShader(type);63 if (!s) return null;64 gl!.shaderSource(s, src);65 gl!.compileShader(s);66 if (!gl!.getShaderParameter(s, gl!.COMPILE_STATUS)) {67 console.warn("[fd-shader]", gl!.getShaderInfoLog(s));68 return null;69 }70 return s;71 };72 const v = make(gl.VERTEX_SHADER, vs);73 const f = make(gl.FRAGMENT_SHADER, fs);74 const prog = gl.createProgram();75 if (!v || !f || !prog) return null;76 gl.attachShader(prog, v);77 gl.attachShader(prog, f);78 gl.bindAttribLocation(prog, 0, "aP");79 gl.linkProgram(prog);80 if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return null;81 gl.useProgram(prog);82 const buf = gl.createBuffer();83 gl.bindBuffer(gl.ARRAY_BUFFER, buf);84 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);85 gl.enableVertexAttribArray(0);86 gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);87 const u: Stage["u"] = {};88 for (const m of frag.matchAll(/uniform\s+\w+\s+(\w+)/g)) u[m[1]] = gl.getUniformLocation(prog, m[1]);89 return { gl, gl2, prog, u, w: 1, h: 1, dpr: 1, reduced: false };90}91 92function useStage(ref: RefObject<HTMLCanvasElement | null>, frag: string, hooks: MutableRefObject<StageHooks>, maxDpr = 2) {93 const [failed, setFailed] = useState(false);94 const kick = useRef<() => void>(() => {});95 useEffect(() => {96 const canvas = ref.current;97 if (!canvas) return;98 const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;99 let stage: Stage | null = null;100 let raf = 0;101 let last = 0;102 let time = 0;103 let visible = true;104 let alive = true;105 const loop = (now: number) => {106 raf = 0;107 if (!stage || !alive) return;108 const dt = last ? Math.min((now - last) / 1000, 0.05) : 1 / 60;109 last = now;110 if (!reduced) time += dt;111 const more = hooks.current.frame(stage, time, dt);112 stage.gl.drawArrays(stage.gl.TRIANGLES, 0, 3);113 if (more && !reduced && visible && !document.hidden) raf = requestAnimationFrame(loop);114 else last = 0;115 };116 const request = () => {117 if (!raf && alive && stage) raf = requestAnimationFrame(loop);118 };119 const resize = () => {120 if (!stage) return;121 const r = canvas.getBoundingClientRect();122 const dpr = Math.min(window.devicePixelRatio || 1, maxDpr);123 const w = Math.max(1, Math.round(r.width * dpr));124 const h = Math.max(1, Math.round(r.height * dpr));125 if (canvas.width !== w || canvas.height !== h) {126 canvas.width = w;127 canvas.height = h;128 }129 stage.w = w;130 stage.h = h;131 stage.dpr = dpr;132 stage.gl.viewport(0, 0, w, h);133 request();134 };135 const init = () => {136 stage = createStage(canvas, frag);137 if (!stage) {138 setFailed(true);139 return;140 }141 stage.reduced = reduced;142 hooks.current.setup?.(stage);143 resize();144 };145 const onLost = (e: Event) => {146 e.preventDefault();147 cancelAnimationFrame(raf);148 raf = 0;149 stage = null;150 };151 const onRestored = () => init();152 const onVis = () => !document.hidden && request();153 canvas.addEventListener("webglcontextlost", onLost);154 canvas.addEventListener("webglcontextrestored", onRestored);155 document.addEventListener("visibilitychange", onVis);156 const ro = new ResizeObserver(resize);157 ro.observe(canvas);158 const io = new IntersectionObserver(([e]) => {159 visible = e.isIntersecting;160 if (visible) request();161 });162 io.observe(canvas);163 kick.current = request;164 init();165 return () => {166 alive = false;167 cancelAnimationFrame(raf);168 ro.disconnect();169 io.disconnect();170 canvas.removeEventListener("webglcontextlost", onLost);171 canvas.removeEventListener("webglcontextrestored", onRestored);172 document.removeEventListener("visibilitychange", onVis);173 kick.current = () => {};174 };175 }, [ref, frag, hooks, maxDpr]);176 return { failed, kick };177}178 179function makeTexture(gl: GL, filter: number, wrap: number) {180 const t = gl.createTexture();181 gl.bindTexture(gl.TEXTURE_2D, t);182 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);183 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);184 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);185 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);186 return t;187}188 189const hexToRgb = (hex: string): [number, number, number] => {190 let h = hex.replace("#", "").trim();191 if (h.length === 3) h = h.split("").map((c) => c + c).join("");192 const n = parseInt(h.slice(0, 6), 16) || 0;193 return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];194};195 196/** 64×64 blue-noise threshold map (void-and-cluster, void-filling pass). Cached. */197let blueNoiseCache: Uint8Array | null = null;198function blueNoise(): Uint8Array {199 if (blueNoiseCache) return blueNoiseCache;200 const S = 64;201 const N = S * S;202 const energy = new Float32Array(N);203 const rank = new Int32Array(N).fill(-1);204 const R = 6;205 const kern: number[] = [];206 for (let y = -R; y <= R; y++) for (let x = -R; x <= R; x++) kern.push(x, y, Math.exp(-(x * x + y * y) / (2 * 1.9 * 1.9)));207 let seed = 7;208 for (let i = 0; i < N; i++) {209 seed = (seed * 16807) % 2147483647;210 energy[i] = (seed / 2147483647) * 1e-4;211 }212 for (let k = 0; k < N; k++) {213 let best = 0;214 let bv = Infinity;215 for (let i = 0; i < N; i++) if (rank[i] < 0 && energy[i] < bv) { bv = energy[i]; best = i; }216 rank[best] = k;217 const bx = best % S;218 const by = (best / S) | 0;219 for (let j = 0; j < kern.length; j += 3) {220 const x = (bx + kern[j] + S) % S;221 const y = (by + kern[j + 1] + S) % S;222 energy[y * S + x] += kern[j + 2];223 }224 }225 const out = new Uint8Array(N);226 for (let i = 0; i < N; i++) out[i] = Math.floor((rank[i] * 256) / N);227 blueNoiseCache = out;228 return out;229}230 231/* ───────────────────────── shader ───────────────────────── */232 233const FRAG = /* glsl */ `234uniform sampler2D uImg;235uniform sampler2D uNoise;236uniform vec2 uRes;237uniform vec2 uImgSize;238uniform float uPx;239uniform float uAlgo;240uniform vec3 uPal[4];241uniform float uN;242uniform float uContrast;243uniform float uBright;244uniform vec3 uLens;245uniform float uRadius;246uniform float uMode;247 248float bayer2(vec2 a){ a = floor(a); return fract(a.x * .5 + a.y * a.y * .75); }249float bayer4(vec2 a){ return bayer2(.5 * a) * .25 + bayer2(a); }250float bayer8(vec2 a){ return bayer4(.5 * a) * .25 + bayer2(a); }251 252float threshold(vec2 cell){253 if (uAlgo < .5) return bayer2(cell) + .125;254 if (uAlgo < 1.5) return bayer4(cell) + .03125;255 if (uAlgo < 2.5) return bayer8(cell) + .0078125;256 return texture2D(uNoise, (mod(cell, 64.) + .5) / 64.).r + .002;257}258 259vec2 cover(vec2 uv){260 float ra = uRes.x / uRes.y;261 float ia = uImgSize.x / uImgSize.y;262 vec2 s = ra > ia ? vec2(1., ia / ra) : vec2(ra / ia, 1.);263 return (uv - .5) * s + .5;264}265 266vec3 pal(float i){267 vec3 c = uPal[0];268 c = mix(c, uPal[1], step(.5, i));269 c = mix(c, uPal[2], step(1.5, i));270 c = mix(c, uPal[3], step(2.5, i));271 return c;272}273 274void main(){275 vec2 fc = gl_FragCoord.xy;276 float d = length(fc - uLens.xy);277 float lens = (1. - smoothstep(uRadius * .35, uRadius, d)) * uLens.z;278 279 float cell = uPx;280 if (uMode < .5) cell = max(1., floor(mix(uPx, max(1., uPx * .34), lens) + .5));281 vec2 id = floor(fc / cell);282 vec2 center = (id + .5) * cell;283 vec3 src = texture2D(uImg, cover(center / uRes)).rgb;284 float l = dot(src, vec3(.2126, .7152, .0722));285 l = clamp((l - .5) * uContrast + .5 + uBright, 0., 1.);286 287 float t = threshold(id);288 float n = uN - 1.;289 float v = l * n;290 float idx = min(floor(v) + step(t, fract(v)), n);291 vec3 col = pal(idx);292 293 if (uMode > .5 && uMode < 1.5) {294 // invert, the loupe edge is itself dithered295 float inside = step(t, lens);296 col = mix(col, pal(n - idx), inside);297 } else if (uMode > 1.5 && uMode < 2.5) {298 vec3 photo = texture2D(uImg, cover(fc / uRes)).rgb;299 col = mix(col, photo, step(t, lens));300 }301 gl_FragColor = vec4(col, 1.);302}303`;304 305/* ───────────────────────── component ───────────────────────── */306 307export type DitherAlgorithm = "bayer2" | "bayer4" | "bayer8" | "blue-noise";308 309export interface DitherImageProps {310 src?: string;311 draw?: (ctx: CanvasRenderingContext2D, w: number, h: number) => void;312 /** Size of the procedural `draw` canvas. Default [900, 1200]. */313 drawSize?: [number, number];314 palette?: string[];315 pixelSize?: number;316 algorithm?: DitherAlgorithm;317 contrast?: number;318 brightness?: number;319 lens?: "sharpen" | "invert" | "reveal" | "none";320 lensRadius?: number;321 alt?: string;322 className?: string;323 style?: CSSProperties;324 children?: ReactNode;325}326 327const ALGOS: Record<DitherAlgorithm, number> = { bayer2: 0, bayer4: 1, bayer8: 2, "blue-noise": 3 };328const MODES = { sharpen: 0, invert: 1, reveal: 2, none: 0 };329 330export function DitherImage({331 src,332 draw,333 drawSize = [900, 1200],334 palette = ["#121212", "#F2EFE8"],335 pixelSize = 3,336 algorithm = "bayer8",337 contrast = 1.15,338 brightness = 0,339 lens = "sharpen",340 lensRadius = 140,341 alt = "",342 className,343 style,344 children,345}: DitherImageProps) {346 const rootRef = useRef<HTMLDivElement>(null);347 const canvasRef = useRef<HTMLCanvasElement>(null);348 const props = useRef({ palette, pixelSize, algorithm, contrast, brightness, lens, lensRadius });349 props.current = { palette, pixelSize, algorithm, contrast, brightness, lens, lensRadius };350 const source = useRef<{ el: TexImageSource | null; w: number; h: number; dirty: boolean }>({ el: null, w: 1, h: 1, dirty: false });351 const pointer = useRef({ x: 0, y: 0, tx: 0, ty: 0, on: 0, ton: 0, seen: false });352 const fallbackRef = useRef<HTMLCanvasElement>(null);353 const [srcVersion, setSrcVersion] = useState(0);354 const tex = useRef<{ img: WebGLTexture | null; noise: WebGLTexture | null }>({ img: null, noise: null });355 356 const hooks = useRef<StageHooks>({357 setup(s) {358 const { gl } = s;359 gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);360 tex.current.noise = makeTexture(gl, gl.NEAREST, gl.REPEAT);361 gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, 64, 64, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, blueNoise());362 tex.current.img = makeTexture(gl, gl.LINEAR, gl.CLAMP_TO_EDGE);363 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([128, 128, 128, 255]));364 source.current.dirty = !!source.current.el;365 gl.uniform1i(s.u.uImg, 0);366 gl.uniform1i(s.u.uNoise, 1);367 },368 frame(s, _t, dt) {369 const { gl, u } = s;370 const p = props.current;371 const src = source.current;372 gl.activeTexture(gl.TEXTURE1);373 gl.bindTexture(gl.TEXTURE_2D, tex.current.noise);374 gl.activeTexture(gl.TEXTURE0);375 gl.bindTexture(gl.TEXTURE_2D, tex.current.img);376 if (src.dirty && src.el) {377 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);378 try {379 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src.el);380 } catch {381 /* tainted image (no CORS), keep placeholder */382 }383 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);384 src.dirty = false;385 }386 const pt = pointer.current;387 const k = s.reduced ? 1 : 1 - Math.exp(-dt * 16);388 const kOn = s.reduced ? 1 : 1 - Math.exp(-dt * 7);389 pt.x += (pt.tx - pt.x) * k;390 pt.y += (pt.ty - pt.y) * k;391 pt.on += (pt.ton - pt.on) * kOn;392 const pal = p.palette.slice(0, 4);393 while (pal.length < 2) pal.push("#ffffff");394 const flat: number[] = [];395 for (let i = 0; i < 4; i++) flat.push(...hexToRgb(pal[Math.min(i, pal.length - 1)]));396 gl.uniform2f(u.uRes, s.w, s.h);397 gl.uniform2f(u.uImgSize, src.w, src.h);398 gl.uniform1f(u.uPx, Math.max(1, Math.round(p.pixelSize * s.dpr)));399 gl.uniform1f(u.uAlgo, ALGOS[p.algorithm] ?? 2);400 gl.uniform3fv(u.uPal, new Float32Array(flat));401 gl.uniform1f(u.uN, pal.length);402 gl.uniform1f(u.uContrast, p.contrast);403 gl.uniform1f(u.uBright, p.brightness);404 gl.uniform3f(u.uLens, pt.x * s.dpr, s.h - pt.y * s.dpr, p.lens === "none" ? 0 : pt.on);405 gl.uniform1f(u.uRadius, p.lensRadius * s.dpr);406 gl.uniform1f(u.uMode, MODES[p.lens] ?? 0);407 const settling = Math.abs(pt.tx - pt.x) + Math.abs(pt.ty - pt.y) > 0.3 || Math.abs(pt.ton - pt.on) > 0.004;408 return settling;409 },410 });411 const { failed, kick } = useStage(canvasRef, FRAG, hooks);412 413 // load / draw source414 useEffect(() => {415 let cancelled = false;416 if (src) {417 const img = new Image();418 img.crossOrigin = "anonymous";419 img.decoding = "async";420 img.onload = () => {421 if (cancelled) return;422 source.current = { el: img, w: img.naturalWidth, h: img.naturalHeight, dirty: true };423 kick.current();424 setSrcVersion((v) => v + 1);425 };426 img.src = src;427 } else if (draw) {428 const c = document.createElement("canvas");429 c.width = drawSize[0];430 c.height = drawSize[1];431 const ctx = c.getContext("2d");432 if (ctx) draw(ctx, c.width, c.height);433 source.current = { el: c, w: c.width, h: c.height, dirty: true };434 kick.current();435 setSrcVersion((v) => v + 1);436 }437 return () => {438 cancelled = true;439 };440 // eslint-disable-next-line react-hooks/exhaustive-deps441 }, [src, draw, drawSize[0], drawSize[1], kick]);442 443 // No WebGL: dither once on the CPU into a 2D canvas (ordered Bayer 8×8), so the fallback still shows the image.444 useEffect(() => {445 const out = fallbackRef.current;446 const srcEl = source.current.el as CanvasImageSource | null;447 if (!failed || !out || !srcEl) return;448 const r = out.getBoundingClientRect();449 const cell = Math.max(1, Math.round(pixelSize));450 const W = Math.max(1, Math.round(r.width / cell));451 const H = Math.max(1, Math.round(r.height / cell));452 out.width = W;453 out.height = H;454 const ctx = out.getContext("2d");455 if (!ctx) return;456 const { w, h } = source.current;457 const k = Math.max(W / w, H / h);458 try {459 ctx.drawImage(srcEl, (W - w * k) / 2, (H - h * k) / 2, w * k, h * k);460 const img = ctx.getImageData(0, 0, W, H);461 const pal = palette.slice(0, 4).map(hexToRgb);462 const n = pal.length - 1;463 const base = [0, 2, 3, 1];464 for (let y = 0; y < H; y++)465 for (let x = 0; x < W; x++) {466 let b = 0;467 for (let q = 0; q < 3; q++) b += base[(((y >> q) & 1) << 1) | ((x >> q) & 1)] * 4 ** (2 - q);468 const t = (b + 0.5) / 64;469 const i = (y * W + x) * 4;470 let l = (0.2126 * img.data[i] + 0.7152 * img.data[i + 1] + 0.0722 * img.data[i + 2]) / 255;471 l = Math.min(1, Math.max(0, (l - 0.5) * contrast + 0.5 + brightness));472 const v = l * n;473 const idx = Math.min(n, Math.floor(v) + (v - Math.floor(v) > t ? 1 : 0));474 img.data[i] = pal[idx][0] * 255;475 img.data[i + 1] = pal[idx][1] * 255;476 img.data[i + 2] = pal[idx][2] * 255;477 img.data[i + 3] = 255;478 }479 ctx.putImageData(img, 0, 0);480 } catch {481 /* tainted canvas, CSS halftone shows through */482 }483 }, [failed, srcVersion, palette.join(), pixelSize, contrast, brightness]);484 485 // redraw when visual props change486 useEffect(() => kick.current(), [palette.join(), pixelSize, algorithm, contrast, brightness, lens, lensRadius, kick]);487 488 // pointer → loupe489 useEffect(() => {490 const el = rootRef.current;491 if (!el) return;492 const move = (e: PointerEvent) => {493 const r = el.getBoundingClientRect();494 const pt = pointer.current;495 pt.tx = e.clientX - r.left;496 pt.ty = e.clientY - r.top;497 if (!pt.seen) {498 pt.x = pt.tx;499 pt.y = pt.ty;500 pt.seen = true;501 }502 pt.ton = 1;503 kick.current();504 };505 const leave = () => {506 pointer.current.ton = 0;507 pointer.current.seen = false;508 kick.current();509 };510 el.addEventListener("pointermove", move);511 el.addEventListener("pointerdown", move);512 el.addEventListener("pointerleave", leave);513 el.addEventListener("pointercancel", leave);514 return () => {515 el.removeEventListener("pointermove", move);516 el.removeEventListener("pointerdown", move);517 el.removeEventListener("pointerleave", leave);518 el.removeEventListener("pointercancel", leave);519 };520 }, [kick]);521 522 return (523 <div ref={rootRef} className={`fd-dimg${className ? " " + className : ""}`} style={style}>524 <style>{css}</style>525 {failed ? (526 <>527 <div className="fd-dimg-fallback" aria-hidden="true" />528 <canvas ref={fallbackRef} className="fd-dimg-canvas" role={alt ? "img" : undefined} aria-label={alt || undefined} aria-hidden={alt ? undefined : true} />529 </>530 ) : (531 <canvas ref={canvasRef} className="fd-dimg-canvas" role={alt ? "img" : undefined} aria-label={alt || undefined} aria-hidden={alt ? undefined : true} />532 )}533 {children ? <div className="fd-dimg-overlay">{children}</div> : null}534 </div>535 );536}537 538const css = `539.fd-dimg, .fd-dimg *, .fd-dimg *::before, .fd-dimg *::after { box-sizing: border-box; }540.fd-dimg {541 position: relative; display: block; margin: 0; padding: 0; border: 0;542 overflow: hidden; border-radius: var(--fd-dimg-radius, 0px);543 background: #121212; color: inherit; touch-action: pan-y;544 isolation: isolate;545}546.fd-dimg-canvas {547 position: absolute; inset: 0; display: block; width: 100%; height: 100%;548 margin: 0; padding: 0; border: 0; image-rendering: pixelated;549}550.fd-dimg-fallback {551 position: absolute; inset: 0; margin: 0; padding: 0; border: 0;552 background: var(--fd-dimg-fallback, radial-gradient(circle at 50% 38%, #F2EFE8 0 18%, #8A857D 42%, #121212 78%));553 -webkit-mask: radial-gradient(circle, #000 1.1px, transparent 1.6px) 0 0 / 4px 4px;554 mask: radial-gradient(circle, #000 1.1px, transparent 1.6px) 0 0 / 4px 4px;555}556.fd-dimg-overlay { position: absolute; inset: 0; margin: 0; padding: 0; pointer-events: none; }557.fd-dimg-overlay a, .fd-dimg-overlay button { pointer-events: auto; }558`;559 560/* ───────────────────────── demo ───────────────────────── */561 562function drawScene(ctx: CanvasRenderingContext2D, w: number, h: number) {563 const sky = ctx.createLinearGradient(0, 0, 0, h);564 sky.addColorStop(0, "#2a2a2a");565 sky.addColorStop(0.62, "#d8d8d8");566 sky.addColorStop(1, "#f4f4f4");567 ctx.fillStyle = sky;568 ctx.fillRect(0, 0, w, h);569 const cx = w * 0.5;570 const cy = h * 0.46;571 const r = Math.min(w, h) * 0.3;572 const orb = ctx.createRadialGradient(cx - r * 0.35, cy - r * 0.4, r * 0.05, cx, cy, r);573 orb.addColorStop(0, "#ffffff");574 orb.addColorStop(0.55, "#9a9a9a");575 orb.addColorStop(1, "#111111");576 ctx.fillStyle = orb;577 ctx.beginPath();578 ctx.arc(cx, cy, r, 0, Math.PI * 2);579 ctx.fill();580 const floor = ctx.createRadialGradient(cx, cy + r * 1.15, 0, cx, cy + r * 1.15, r * 1.1);581 floor.addColorStop(0, "rgba(0,0,0,0.55)");582 floor.addColorStop(1, "rgba(0,0,0,0)");583 ctx.fillStyle = floor;584 ctx.save();585 ctx.translate(0, cy + r * 1.15);586 ctx.scale(1, 0.18);587 ctx.translate(0, -(cy + r * 1.15));588 ctx.fillRect(0, 0, w, h * 6);589 ctx.restore();590}591 592export function Demo() {593 return (594 <div className="fd-dimgd">595 <style>{demoCss}</style>596 <DitherImage597 className="fd-dimgd-frame"598 draw={drawScene}599 drawSize={[900, 1100]}600 palette={["#1d1d1f", "#8a8a8e", "#f6f6f4"]}601 pixelSize={3}602 algorithm="bayer8"603 alt="A sphere dithered in three inks"604 />605 </div>606 );607}608 609const F = `ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif`;610 611const demoCss = `612.fd-dimgd,.fd-dimgd *,.fd-dimgd *::before,.fd-dimgd *::after{box-sizing:border-box}613.fd-dimgd{display:flex;align-items:center;justify-content:center;min-height:100vh;width:100%;margin:0;padding:32px 20px;overflow:hidden;color:#1d1d1f;font:400 15px/1.4 ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif;letter-spacing:normal;background:#f2f2f2}614.fd-dimgd-frame.fd-dimg{width:min(100%,360px);aspect-ratio:9/11;margin:0;padding:0;--fd-dimg-radius:20px;cursor:crosshair;box-shadow:0 1px 1px rgba(0,0,0,.06),0 24px 60px -24px rgba(0,0,0,.35)}615`;More Dither. Same file contract.
Questions about Dither Image
Run npx shadcn@latest add https://freedesignmd.com/r/dither-image.json, or open the page and copy the file into your project. It has zero dependencies besides React. What you copy is the exact file that renders the live demo.
Dither shader for images: Bayer and blue-noise dithering to 2 to 4 inks, with a cursor loupe that sharpens, inverts or reveals. It is a free, MIT-licensed React dither component from the freedesignmd library.
Yes. It is free and MIT-licensed, use, modify and ship it in personal and commercial projects without attribution.
WebGL2 with WebGL1 fallback. Without WebGL a CSS halftone gradient is shown.
Yes. It is a plain React component with its own styles, so it runs in Next.js, Vite, Remix and Lovable projects, and it needs no Tailwind setup. It has zero dependencies besides React.


