{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"ascii-halftone-canvas","type":"registry:component","title":"ASCII Halftone Canvas","description":"Turns any canvas drawing into live ASCII art, sampled one pixel per glyph.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/ascii-halftone-canvas.tsx","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\nconst RAMP = \" .:-=+*#%@\";\n\nexport function AsciiHalftoneCanvas({\n  draw,\n  cols = 54,\n  invert = false,\n  animate = true,\n  speed = 0.35,\n}: {\n  /**\n   * Paints the source frame. Receives a 2D context already sized to the\n   * CHARACTER grid (cols x lines), plus `t`, a seconds counter for animation.\n   * Taking a draw callback instead of an image src is deliberate — see the\n   * tainting note below.\n   */\n  draw: (ctx: CanvasRenderingContext2D, w: number, h: number, t: number) => void;\n  cols?: number;\n  invert?: boolean;\n  /** Advance the seconds counter passed to the draw callback. Off freezes it. */\n  animate?: boolean;\n  /** Radians per second the key light travels. Ambient is well under 1. */\n  speed?: number;\n}) {\n  const preRef = useRef<HTMLPreElement>(null);\n  const frame = useRef<number | null>(null);\n  const opts = useRef({ cols, invert, animate, draw, speed });\n\n  useEffect(() => {\n    opts.current = { cols, invert, animate, draw, speed };\n  }, [cols, invert, animate, draw, speed]);\n\n  useEffect(() => {\n    const canvas = document.createElement(\"canvas\");\n    // willReadFrequently tells the browser to keep this canvas on the CPU.\n    // Without it, a GPU-backed canvas has to be read back every frame, which\n    // is far slower for a getImageData-per-frame workload like this one.\n    const context = canvas.getContext(\"2d\", { willReadFrequently: true });\n    if (!context) return;\n    // Re-bound so render() below, a hoisted function, sees it as non-null\n    // under strict TypeScript.\n    const ctx: CanvasRenderingContext2D = context;\n\n    let t = 0;\n    let last = 0;\n\n    function render() {\n      const { cols: rawCols, invert: inv, animate: anim, draw: paint, speed: sp } = opts.current;\n      // BOUNDED BEFORE IT SIZES A CANVAS.\n      //\n      // cols is a CHARACTER count, but nothing in the type says so — it is\n      // just a number. A copier who reads it as pixels and passes 5000 gets\n      // a 5000x2100 canvas reallocated every frame: roughly 42MB per\n      // getImageData call, sixty times a second, wrapped around a\n      // ten-million-iteration string concatenation inside the rAF callback.\n      // The frame is gone long before anything paints. The ceiling here is\n      // what makes that unreachable.\n      const c = Math.min(200, Math.max(4, Math.round(Number(rawCols) || 54)));\n      // The offscreen canvas is sized to the CHARACTER grid, not the display\n      // size: one pixel read per glyph, so cost tracks the number of\n      // characters shown rather than the resolution.\n      const lines = Math.max(4, Math.round(c * 0.42)); // glyph aspect ratio\n      canvas.width = c;\n      canvas.height = lines;\n      //\n      // TIME-BASED, NOT PER-FRAME.\n      //\n      // Advancing a fixed amount every frame ties the animation to the refresh\n      // rate: the same code runs at DOUBLE speed on a 120Hz display and half\n      // speed on a throttled tab, and you never see it on the machine you\n      // built it on. The delta is clamped so a backgrounded tab does not\n      // return and jump the light a quarter of the way round its orbit.\n      //\n      const now = performance.now();\n      const dt = last ? Math.min(100, now - last) : 16.7;\n      last = now;\n      if (anim) t += (dt / 1000) * sp;\n\n      paint(ctx, c, lines, t);\n\n      const data = ctx.getImageData(0, 0, c, lines).data;\n      let out = \"\";\n      for (let y = 0; y < lines; y++) {\n        for (let x = 0; x < c; x++) {\n          const i = (y * c + x) * 4;\n          // Rec. 601 luma — perceptual, unlike a flat (r+g+b)/3 average.\n          const lum = (0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]) / 255;\n          const v = inv ? 1 - lum : lum;\n          out += RAMP[Math.min(RAMP.length - 1, Math.floor(v * RAMP.length))];\n        }\n        out += \"\\n\";\n      }\n\n      // Written straight to the DOM node. Holding this in React state would\n      // mean a full component render 60 times a second to update a string.\n      if (preRef.current) preRef.current.textContent = out;\n\n      frame.current = requestAnimationFrame(render);\n    }\n\n    frame.current = requestAnimationFrame(render);\n    return () => {\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n    };\n  }, []);\n\n  return (\n    <pre\n      ref={preRef}\n      className=\"select-none font-mono leading-[0.78]\"\n      style={{ fontSize: 8 }}\n    />\n  );\n}\n","type":"registry:component","target":"components/viberdy/ascii-halftone-canvas.tsx"}],"meta":{"tier":"free","tags":["ascii","canvas","halftone","retro"],"href":"https://viberdy.dev/library/ascii-halftone-canvas","aiPrompt":"Create a React + Tailwind component named AsciiHalftoneCanvas — renders anything drawable on a canvas as animated ASCII art.\n\nAPI:\n- Takes a `draw(ctx, width, height, t)` callback that paints the source frame, plus `cols` and `invert`.\n- Taking a draw callback instead of an image `src` is DELIBERATE: getImageData throws a SecurityError on a canvas that has had a cross-origin image drawn into it, which is the failure every image-based ASCII converter hits the first time it is pointed at a CDN URL. A draw callback lets the caller decide how the source gets there.\n\nAlgorithm:\n- Create ONE offscreen canvas and size it to the CHARACTER grid (cols x round(cols * 0.42) — the 0.42 compensates for monospace glyphs being taller than wide). Not the display size: this way there is exactly one pixel read per glyph, so cost tracks character count rather than resolution.\n- Each frame: call draw(), then getImageData once, convert each pixel to luma with the Rec. 601 weights (0.299 R + 0.587 G + 0.114 B) — NOT a flat (r+g+b)/3 average, which misjudges perceived brightness badly on saturated colors — and map it into a density ramp \" .:-=+*#%@\".\n- Write the assembled string straight to a <pre> node's textContent via a ref. Do NOT keep the rows in React state: that is a full component render 60 times a second to update a string.\n- Pass { willReadFrequently: true } to getContext(\"2d\"). Without it a GPU-backed canvas must be read back every frame, which is much slower for a getImageData-per-frame workload.\n- Cancel the animation frame on unmount.\n\nAccessibility: wrap in an element with role=\"img\" and a descriptive aria-label, and mark the <pre> aria-hidden — otherwise a screen reader reads thousands of punctuation characters.\n\nProps: draw (callback), cols (number), invert (boolean), animate (boolean), speed (number, radians per second).\n\nOutput a single self-contained \"use client\" component.","license":"https://viberdy.dev/license"}}