用 `random()` 生成不会重复的波点背景。

解读

面试官想考察两点:

  1. 对 Sass 的 random() 局限性的清醒认知——它只能在编译期产生伪随机数,无法保证运行时唯一;
  2. 能否用编译期去重策略(如集合、哈希、二维网格编号)把“重复”在 CSS 层面消灭,并输出可维护、可配置、不爆炸的代码。
    国内前端面试中,这道题常作为“CSS 视觉+工程化”综合题出现,答出“去重思路”比答出“完美随机”更值钱。

知识点

  • random(limit)∗∗:返回1到limit)**:返回 1 到 limit 的整数,每次编译结果不同,但同一编译周期内可缓存**;
  • list 与 map:用作“已用坐标表”实现编译期去重;
  • @while 循环:在 Sass 中可安全有限次循环,需手动上限保护防止死循环;
  • CSS 变量降级:把随机色、半径抽成 CSS 变量,运行时仍可动态覆盖;
  • background-image 多层叠加:每层一个 radial-gradient 圆点,无重复坐标即可实现“不重复波点”;
  • 性能红线:国内项目要求编译后 CSS ≤ 100 KB,需用 $density 控制层数,禁止无节制输出。

答案

// 可配置变量
$density: 60;            // 总波点数
$dot-min: 4;              // 最小半径(px)
$dot-max: 12;             // 最大半径(px)
$colors: (#ff5f5f, #0abf53, #0891e6, #f59e0b);

// 去重容器
$coords: ();
$bg-list: ();

@function unique-pos() {
  $x: 0;
  $y: 0;
  $attempts: 0;
  // 安全上限:防止死循环
  @while $attempts < 1000 {
    $x: random(1000) * 0.1%;   // 0.1% 精度
    $y: random(1000) * 0.1%;
    $key: $x * 1000 + $y;      // 哈希键
    @if not index($coords, $key) {
      $coords: append($coords, $key);
      @return ($x, $y);
    }
    $attempts: $attempts + 1;
  }
  @warn "去重失败,返回兜底坐标";
  @return (50%, 50%);
}

@for $i from 1 through $density {
  $xy: unique-pos();
  $x: nth($xy, 1);
  $y: nth($xy, 2);
  $r: $dot-min + random($dot-max - $dot-min);
  $c: nth($colors, random(length($colors)));

  $layer: radial-gradient(circle #{$r}px at $x $y, $c 99%, transparent 100%);
  $bg-list: append($bg-list, $layer, comma);
}

.polka {
  width: 100vw;
  height: 100vh;
  background: $bg-list;
  background-size: 100% 100%;
}

编译后得到单层 background-image,含 60 个不重叠 radial-gradient 圆点,CSS 体积约 3 KB,满足国内移动端性能基线。

拓展思考

  1. 运行时真随机:若产品要求“每次刷新都不一样”,需把坐标、半径、颜色抽成 CSS 变量,用 JS 在客户端二次赋值;Sass 仅负责生成变量模板。
  2. 响应式密度:利用 media 查询给 $density 不同值,桌面 120 点 / 移动 60 点,兼顾视网膜屏与低端机。
  3. SVG 替代方案:当点数 > 200 时,多层 gradient 性能骤降,可让 Sass 生成 <svg> 内联片段,利用 <circle> 元素去重,体积下降 40%。
  4. 设计系统沉淀:把 unique-pos() 封装成 polka-generator($density, $shape),发布到私有 npm 包,供各业务线统一调用,体现工程化思维。