Iridescence
虹彩偏移波動的著色器背景:以 canvas 2D 近似 iridescence shader,可選滑鼠反應。
以 canvas 2D 逐格計算並拉伸插值,近似經典 iridescence 著色器的虹彩波動,不依賴 WebGL。
載入預覽⋯
Playground
即時調整 props、程式碼片段同步更新——直接試出你要的樣子再複製。
1
0.1
96
<Iridescence />
安裝
npx shadcn@latest add https://webberui.com/r/iridescence.json或在 components.json 設定 registries 後,改用 @webberui/iridescence 安裝。
安裝依賴後,打開 iridescence.json,把 files[0].content 的內容複製到你的 components/ui/iridescence.tsx:
npm install motion clsx tailwind-merge使用
前景內容直接放進 children,佈局(如置中、高度)寫在 className 上:
import { Iridescence } from "@/components/ui/iridescence";
<Iridescence className="flex h-[360px] items-center justify-center rounded-2xl">
<h1 className="text-4xl font-bold text-white">Hero 標題</h1>
</Iridescence>自訂色調、放慢速度並開啟滑鼠反應:
<Iridescence
color={[1, 1, 1]}
speed={0.6}
mouseReact
amplitude={0.2}
className="flex h-[400px] items-center justify-center rounded-2xl"
>
<p className="text-lg text-white">完整虹彩光譜</p>
</Iridescence>color 為各通道 0~1 的 RGB 色調,整體會乘上這個顏色:[1, 1, 1] 保留完整虹彩,越暗越收斂到單一色相。
Props
| Prop | 型別 | 預設值 | 說明 |
|---|---|---|---|
color | [number, number, number] | 偏冷青紫 | 整體色調,各通道 0~1;[1, 1, 1] 為完整虹彩 |
speed | number | 1 | 波動速度倍率 |
amplitude | number | 0.1 | 滑鼠偏移對圖樣的影響幅度(mouseReact 開啟時生效) |
mouseReact | boolean | false | 圖樣是否跟隨滑鼠偏移(僅滑鼠指標生效,觸控不作用) |
detail | number | 96 | 內部取樣邊長(px),越大越細緻但越吃效能 |
children | React.ReactNode | — | 前景內容,疊在虹彩之上 |
className | string | — | 附加到最外層容器的 class |
細節
- 不用 WebGL。 對降取樣網格逐格計算著色器輸出,寫入
ImageData,再由 canvas 以h-full w-full拉伸,靠瀏覽器內建雙線性插值補成平滑虹彩,避免 three.js 這類重相依 - 較長邊固定為
detail,較短邊依容器長寬比縮放,換言之取樣量隨長寬比自適應,維持圖樣不變形 - 繪製迴圈只在掛載時建立一次,
color/speed等 props 透過 ref 即時讀取,改參數不會重建迴圈或閃爍 ResizeObserver監看容器尺寸變化並重配網格;元件卸載時cancelAnimationFrame並中止觀察mouseReact開啟時游標位置正規化為0~1,經amplitude縮放後平移取樣座標,形成圖樣跟隨;只在pointerType === "mouse"時作用- 背景 canvas 整層
pointer-events-none並以-z-10沉到內容之下(容器有isolate建立獨立堆疊上下文),前景互動完全不受影響 - 使用者系統開啟「減少動態效果」時,只繪製一幀靜態虹彩,不啟動動畫迴圈,DOM 結構不變