# Dither image

Ordered Bayer dithering quantized to the theme inks, or to two to four colors of your own.

Source: https://www.ui95.dev/ui/dither-image

## Examples

```tsx
import { DitherImage, type DitherImageColors } from "@/components/ui/dither-image"

import type { ShowcaseDemo } from "../types"

type DitherSetting = {
  label: string
  matrixSize: 4 | 8
  pixelSize: number
  contrast: number
  isAnimated: boolean
  colors?: DitherImageColors
}

const SETTINGS: readonly DitherSetting[] = [
  { label: "bayer 4x4", matrixSize: 4, pixelSize: 2, contrast: 1.2, isAnimated: false },
  { label: "bayer 8x8", matrixSize: 8, pixelSize: 2, contrast: 1.2, isAnimated: false },
  { label: "pixel size 4", matrixSize: 4, pixelSize: 4, contrast: 1.2, isAnimated: false },
  { label: "contrast 0.8", matrixSize: 4, pixelSize: 2, contrast: 0.8, isAnimated: false },
  { label: "contrast 2.0", matrixSize: 4, pixelSize: 2, contrast: 2, isAnimated: false },
  {
    label: "custom colors",
    matrixSize: 4,
    pixelSize: 2,
    contrast: 1.2,
    isAnimated: false,
    colors: ["--ink-0", "var(--desktop)", "--ink-3"],
  },
  {
    label: "two colors",
    matrixSize: 8,
    pixelSize: 2,
    contrast: 1.2,
    isAnimated: false,
    colors: ["--ink-0", "--ink-3"],
  },
  { label: "animated reseed", matrixSize: 8, pixelSize: 2, contrast: 1.3, isAnimated: true },
]

export const demo: ShowcaseDemo = {
  span: "large",
  variants: SETTINGS.map(({ label, ...setting }) => ({
    label,
    render: () => (
      <DitherImage
        src="/eye1.png"
        alt={`Eye dithered with ${label}`}
        width={224}
        height={220}
        className="mx-auto max-w-full"
        {...setting}
      />
    ),
  })),
}
```

## Installation

```bash
npx shadcn@latest add https://www.ui95.dev/r/dither-image.json
```

Run it in a Radix shadcn project that already has the UI95 theme.

Dependencies:

```bash
npm install cn
```

Add these items first:

- [dither-inks](https://www.ui95.dev/ui/dither-inks)

`components/ui/dither-image.tsx`

```tsx
"use client"

import { cn } from "cn"
import * as React from "react"

import type { BayerMatrixSize } from "@/lib/dither/bayer"
import { ditherOnCpu, type DitherRequest } from "@/lib/dither/ditherOnCpu"
import { INK_TOKENS, readInks } from "@/lib/dither/inks"
import { useInkVersion } from "@/lib/dither/useInkVersion"

type DitherImageColors =
  | readonly [string, string]
  | readonly [string, string, string]
  | readonly [string, string, string, string]

type DitherImageProps = Omit<
  React.ComponentProps<"canvas">,
  "width" | "height" | "children"
> & {
  src: string
  alt: string
  width: number
  height: number
  pixelSize?: number
  matrixSize?: BayerMatrixSize
  contrast?: number
  isAnimated?: boolean
  colors?: DitherImageColors
}

const COLOR_TOKENS = ["--dither-ink-0", "--dither-ink-1", "--dither-ink-2", "--dither-ink-3"] as const

function toCssColor(color: string): string {
  return color.startsWith("--") ? `var(${color})` : color
}

function readColorStyle(colors: DitherImageColors | undefined): React.CSSProperties {
  if (!colors) {
    return {}
  }
  return Object.fromEntries(colors.map((color, index) => [COLOR_TOKENS[index], toCssColor(color)]))
}

function readColorTokens(colorCount: number): readonly [string, string, ...string[]] {
  if (colorCount < 2) {
    return INK_TOKENS
  }
  const [first, second, ...rest] = COLOR_TOKENS.slice(0, colorCount)
  return [first, second, ...rest]
}

function useLoadedImage(src: string): HTMLImageElement | null {
  const [image, setImage] = React.useState<HTMLImageElement | null>(null)

  React.useEffect(() => {
    let isCurrent = true
    const loading = new Image()
    loading.src = src
    loading
      .decode()
      .then(() => {
        if (isCurrent) {
          setImage(loading)
        }
      })
      .catch(() => {
        if (isCurrent) {
          setImage(null)
        }
      })
    return () => {
      isCurrent = false
    }
  }, [src])

  return image
}

const RESEED_FPS = 12

function useReseed(isAnimated: boolean): number {
  const [seed, setSeed] = React.useState(0)

  React.useEffect(() => {
    if (!isAnimated) {
      return
    }
    const interval = window.setInterval(
      () => setSeed((current) => current + 1),
      1000 / RESEED_FPS
    )
    return () => window.clearInterval(interval)
  }, [isAnimated])

  return seed
}

function DitherImage({
  src,
  alt,
  width,
  height,
  pixelSize = 2,
  matrixSize = 4,
  contrast = 1.2,
  isAnimated = false,
  colors,
  className,
  style,
  ...props
}: DitherImageProps) {
  const canvasRef = React.useRef<HTMLCanvasElement>(null)
  const image = useLoadedImage(src)
  const inkVersion = useInkVersion()
  const seed = useReseed(isAnimated)
  const outputWidth = Math.max(1, Math.round(width / pixelSize))
  const outputHeight = Math.max(1, Math.round(height / pixelSize))
  const colorKey = colors?.join("|") ?? ""
  const colorCount = colors?.length ?? 0

  React.useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas || !image) {
      return
    }
    const request: DitherRequest = {
      source: image,
      width: outputWidth,
      height: outputHeight,
      matrixSize,
      contrast,
      seed,
    }
    const dithered = ditherOnCpu(request, readInks(canvas, readColorTokens(colorCount)))
    if (dithered) {
      canvas.getContext("2d")?.putImageData(dithered, 0, 0)
    }
  }, [image, inkVersion, seed, outputWidth, outputHeight, matrixSize, contrast, colorCount, colorKey])

  return (
    <canvas
      ref={canvasRef}
      role="img"
      aria-label={alt}
      data-slot="dither-image"
      width={outputWidth}
      height={outputHeight}
      className={cn("block pixelated", className)}
      style={{ width, height, ...readColorStyle(colors), ...style }}
      {...props}
    />
  )
}

export { DitherImage }
export type { DitherImageColors, DitherImageProps }
```

`lib/dither/bayer.ts`

```tsx
export type BayerMatrixSize = 4 | 8

function readBayer2(x: number, y: number): number {
  const value = (Math.floor(x) * 0.5 + Math.floor(y) * Math.floor(y) * 0.75) % 1
  return value < 0 ? value + 1 : value
}

function readBayer4(x: number, y: number): number {
  return readBayer2(x * 0.5, y * 0.5) * 0.25 + readBayer2(x, y)
}

function readBayer8(x: number, y: number): number {
  return readBayer4(x * 0.5, y * 0.5) * 0.25 + readBayer2(x, y)
}

const BAYER_READERS: Record<BayerMatrixSize, (x: number, y: number) => number> = {
  4: readBayer4,
  8: readBayer8,
}

export function readBayerThreshold(
  x: number,
  y: number,
  size: BayerMatrixSize
): number {
  return BAYER_READERS[size](x, y)
}
```

`lib/dither/ditherOnCpu.ts`

```tsx
import { type BayerMatrixSize, readBayerThreshold } from "./bayer"
import type { InkPalette } from "./inks"

export type DitherRequest = {
  source: CanvasImageSource
  width: number
  height: number
  matrixSize: BayerMatrixSize
  contrast: number
  seed: number
}

const SEED_OFFSETS = [
  [0, 0],
  [1, 2],
  [3, 1],
  [2, 3],
  [5, 6],
  [7, 4],
] as const

const OPAQUE_FROM_ALPHA = 128

let sampleCanvas: HTMLCanvasElement | null = null

function readSeedOffset(seed: number): readonly [number, number] {
  return SEED_OFFSETS[Math.abs(Math.floor(seed)) % SEED_OFFSETS.length]
}

function readSampleContext(width: number, height: number) {
  sampleCanvas ??= document.createElement("canvas")
  sampleCanvas.width = width
  sampleCanvas.height = height
  return sampleCanvas.getContext("2d", { willReadFrequently: true })
}

export function ditherOnCpu(
  request: DitherRequest,
  inks: InkPalette
): ImageData | null {
  const { width, height, source, matrixSize, contrast } = request
  const context = readSampleContext(width, height)
  if (!context) {
    return null
  }
  context.drawImage(source, 0, 0, width, height)
  const image = context.getImageData(0, 0, width, height)
  const [offsetX, offsetY] = readSeedOffset(request.seed)
  const lastInk = inks.length - 1
  for (let y = 0; y < height; y += 1) {
    for (let x = 0; x < width; x += 1) {
      const offset = (y * width + x) * 4
      if (image.data[offset + 3] < OPAQUE_FROM_ALPHA) {
        image.data[offset + 3] = 0
        continue
      }
      const luminance =
        (image.data[offset] * 0.2126 +
          image.data[offset + 1] * 0.7152 +
          image.data[offset + 2] * 0.0722) /
        255
      const contrasted = Math.min(1, Math.max(0, (luminance - 0.5) * contrast + 0.5))
      const threshold = readBayerThreshold(x + offsetX, y + offsetY, matrixSize)
      const ink = inks[Math.min(lastInk, Math.max(0, Math.floor(contrasted * lastInk + threshold)))]
      image.data[offset] = ink[0]
      image.data[offset + 1] = ink[1]
      image.data[offset + 2] = ink[2]
      image.data[offset + 3] = 255
    }
  }
  return image
}
```

`lib/dither/useInkVersion.ts`

```tsx
"use client"

import { useEffect, useState } from "react"

import { observeInkChange } from "./inks"

export function useInkVersion(): number {
  const [version, setVersion] = useState(0)

  useEffect(() => observeInkChange(() => setVersion((current) => current + 1)), [])

  return version
}
```

## API reference

### DitherImage

| Prop | Type | Default |
| --- | --- | --- |
| `src` * | `string` | - |
| `alt` * | `string` | - |
| `width` * | `number` | - |
| `height` * | `number` | - |
| `pixelSize` | `number` | `2` |
| `matrixSize` | `BayerMatrixSize` | `4` |
| `contrast` | `number` | `1.2` |
| `isAnimated` | `boolean` | `false` |
| `colors` | `DitherImageColors` | - |
