FlickeringGrid
flickering-grid闪烁网格 · canvas 像素方格随机明灭 + ResizeObserver 自适应 + 颜色吃主题 token(逐帧现取)
用法
基础用法
放进 relative + overflow-hidden 容器,用 absolute inset-0 铺满;默认吃主题前景色,4px 方格随机闪烁。
tsx
<div className="relative h-48 w-80 overflow-hidden rounded-xl border border-border bg-surface">
<FlickeringGrid className="absolute inset-0" />
</div>自定义颜色
color 支持 CSS 变量,传强调色 token 并调高 maxOpacity 让网格更醒目。
tsx
<div className="relative h-48 w-80 overflow-hidden rounded-xl border border-border bg-surface">
<FlickeringGrid className="absolute inset-0" color="var(--color-primary)" maxOpacity={0.5} />
</div>方格大小与间距
squareSize / gridGap 决定网格密度,调大方格 + 降低 flickerChance 得到沉稳的大格闪烁。
tsx
<div className="relative h-48 w-80 overflow-hidden rounded-xl border border-border bg-surface">
<FlickeringGrid
className="absolute inset-0"
squareSize={8}
gridGap={4}
flickerChance={0.1}
maxOpacity={0.4}
/>
</div>高频密集闪烁
小方格 + 高 flickerChance 模拟数据流/赛博质感。
tsx
<div className="relative h-48 w-80 overflow-hidden rounded-xl border border-border bg-surface">
<FlickeringGrid
className="absolute inset-0"
squareSize={2}
gridGap={2}
flickerChance={0.7}
maxOpacity={0.25}
/>
</div>何时用
需要科技感/数据感的像素方格背景,且方格随机明灭闪烁时用。基于 canvas,自带 ResizeObserver 跟随容器尺寸;若要静态规则网格(不闪烁、更轻),用 GridPattern;若要点阵用 DotPattern;若要复古透视网格用 RetroGrid。
导入
ts
import { FlickeringGrid } from "@hulianui/ui"Props
继承 HTMLAttributes<HTMLDivElement>,额外:
| 名称 | 类型 | 默认 | 说明 |
|---|---|---|---|
| squareSize | number | 4 | 每个方格边长(px),越小越密 |
| gridGap | number | 6 | 方格间距(px) |
| flickerChance | number | 0.3 | 每帧每格闪烁概率(乘 deltaTime)。0=静态网格,1=高频闪烁 |
| maxOpacity | number | 0.3 | 方格最大不透明度(0~1),越高越明显 |
| color | string | --color-foreground | 方格颜色,任意 CSS 颜色字符串。不传则从容器 color/token 解析 RGB 随主题切换 |
| width | number | — | 固定宽度(px)。不传用 ResizeObserver 跟随容器宽 |
| height | number | — | 固定高度(px)。不传用 ResizeObserver 跟随容器高 |
禁忌 / 坑
- 基于 canvas,须客户端渲染;父容器需
relative+overflow-hidden,组件自身用absolute inset-0铺满。 - 不传
width/height时靠 ResizeObserver 跟随容器,故容器必须有确定尺寸(高度别塌成 0)。 color可传var(--color-*),组件会逐帧 getComputedStyle 解析(与只吃 rgb 的 Particles 不同),但每帧解析有微小成本。
相关
DotPattern · GridPattern · StripedPattern · Spotlight · RetroGrid · Ripple
Playground
<div className="relative h-48 w-80 overflow-hidden rounded-xl">
<FlickeringGrid
className="absolute inset-0"
squareSize={4}
gridGap={6}
flickerChance={0.3}
maxOpacity={0.3}
/>
</div>