{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"grain-overlay","type":"registry:component","title":"Grain Overlay","description":"A subtle animated film-grain texture layered over any section via canvas.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/grain-overlay.tsx","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\n/**\n * SIZED BY ITS PARENT — the parent needs a height.\n *\n * This fills the box it is given: the canvas is absolutely positioned, so\n * the wrapper has nothing in normal flow to derive a height from. Drop it\n * into a plain section or a hero with no height set and it lays out at zero\n * and renders nothing — no error, no warning, no console message, just an\n * empty rectangle, which is the hardest kind of failure to go looking for.\n *\n * Give the parent a real height (h-screen, h-[520px], an aspect-ratio, a\n * grid track) or position this against one that already has one.\n */\nexport function GrainOverlay({\n  density = 3,\n  opacity = 0.08,\n  animated = true,\n  fps = 24,\n}: {\n  density?: number;\n  opacity?: number;\n  /** Grain re-roll rate. Film is 24; the display's 60 is harsher and costlier. */\n  fps?: number;\n  /** Re-roll the noise every frame. Off paints one static field and stops. */\n  animated?: boolean;\n}) {\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n\n    // Measure via ResizeObserver, not a one-time offsetWidth read — in a\n    // scaled thumbnail the canvas can still be 0x0 on first paint, and\n    // createImageData(0, 0) throws.\n    let width = 0;\n    let height = 0;\n    let raf = 0;\n\n    const observer = new ResizeObserver((entries) => {\n      const entry = entries[0];\n      if (!entry) return;\n      width = Math.max(0, Math.round(entry.contentRect.width));\n      height = Math.max(0, Math.round(entry.contentRect.height));\n      canvas.width = width;\n      canvas.height = height;\n      // Assigning width CLEARS the bitmap, and with animation off there is no\n      // loop to put it back — a static grain would sit blank from the first\n      // resize onward. It also covers the very first measurement, where the\n      // canvas is still 0x0 when the initial paint runs.\n      paint();\n    });\n    observer.observe(canvas);\n\n    // GRAIN HAS A FRAME RATE, and it is not the display's. Real film runs at\n    // 24, and re-rolling every pixel 60 times a second is both harsher than\n    // any photochemical grain and two and a half times the work. The loop\n    // still runs every frame — it just only REDRAWS when enough time has\n    // passed, so the cost scales with the chosen rate rather than the monitor.\n    let lastDraw = 0;\n    const minGap = fps > 0 ? 1000 / fps : 0;\n\n    function paint(now?: number) {\n      // A call with no timestamp is a DIRECT one — the first paint, or a\n      // repaint after a resize — and it always draws. Only the rAF-driven\n      // calls, which arrive with a timestamp, are rate-gated. Without this the\n      // static mode never paints at all, because there is no loop behind it to\n      // try again.\n      const stamp = now === undefined ? lastDraw : now;\n      const due = now === undefined || minGap === 0 || stamp - lastDraw >= minGap;\n      if (due && width > 0 && height > 0) {\n        lastDraw = stamp;\n        const imageData = ctx!.createImageData(width, height);\n        const buffer = imageData.data;\n        //\n        // THE STEP MUST BE AT LEAST ONE WHOLE PIXEL.\n        //\n        // density is an ordinary number prop, so 0 is a value someone can\n        // pass — from a quality slider, a CMS field, a parsed query string.\n        // At 0 this reads i += 0: a for-loop that never advances and never\n        // exits. That is not a slow frame, it is a permanently hung tab that\n        // has to be force-killed. The min in the schema constrains this\n        // demo's slider, NOT the component anyone copies out of here.\n        const step = 4 * Math.max(1, Math.round(Number(density) || 1));\n        for (let i = 0; i < buffer.length; i += step) {\n          const shade = Math.random() * 255;\n          buffer[i] = shade;\n          buffer[i + 1] = shade;\n          buffer[i + 2] = shade;\n          buffer[i + 3] = 255;\n        }\n        ctx!.putImageData(imageData, 0, 0);\n      }\n      if (animated) raf = requestAnimationFrame(paint);\n    }\n    paint();\n\n    return () => {\n      observer.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [density, animated, fps]);\n\n  return (\n    <canvas\n      ref={canvasRef}\n      className=\"pointer-events-none absolute inset-0 h-full w-full mix-blend-overlay\"\n      style={{ opacity }}\n    />\n  );\n}\n","type":"registry:component","target":"components/viberdy/grain-overlay.tsx"}],"meta":{"tier":"free","tags":["grain","noise","canvas","texture"],"href":"https://viberdy.dev/library/grain-overlay","aiPrompt":"Create a React \"grain overlay\" background component named GrainOverlay.\n\nBehavior:\n- A full-bleed, absolutely-positioned <canvas> that continuously redraws random monochrome noise (film grain) via requestAnimationFrame, using canvas ImageData directly (not CSS) for real per-pixel randomness.\n- On each frame, create an ImageData buffer sized to the canvas, and for every 4th-byte-aligned pixel (stepped by a density factor to control performance/coarseness), set R=G=B to a random 0-255 shade with full alpha, then putImageData.\n- The canvas is pointer-events-none, positioned absolute inset-0, sized to its parent via a ResizeObserver on the canvas element (not a one-time offsetWidth/offsetHeight read — a canvas rendered into a not-yet-laid-out or scaled container can measure 0x0 on the first paint, and createImageData(0, 0) throws) that updates canvas.width/height and skips painting a frame while either is still zero.\n- Blended onto whatever sits beneath it via mix-blend-mode: overlay, at a low opacity (e.g. 0.08) so it reads as subtle texture, not visible static.\n- Cancel the animation frame loop on unmount.\n\nStyle: this is a texture layer meant to sit on top of a hero, image, or dark section — invisible at a glance but adds tactile, filmic depth. Not a giant loud static effect.\n\nGIVE THE GRAIN ITS OWN FRAME RATE. Real film runs at twenty-four frames a second; re-rolling every pixel at the display's sixty is both harsher than any photochemical grain and two and a half times the work for it. Let the loop run every frame but only REDRAW once enough time has passed, so the cost tracks the chosen rate rather than the monitor. A direct call — the first paint, or a repaint after a resize — must bypass that gate, or the static mode never paints at all, because there is no loop behind it to try again.\n\nCLAMP THE PIXEL STEP TO AT LEAST ONE WHOLE PIXEL. The density prop divides the loop increment, so a zero makes it step by nothing: a for-loop that never advances and never exits, which is a permanently hung tab rather than a slow frame.\n\nProps: opacity, density (pixel step), animated (boolean), fps (grain redraw rate).\n\nOutput a single self-contained \"use client\" component using useRef + useEffect + raw canvas 2D API only (no external noise/shader libraries).","license":"https://viberdy.dev/license"}}