星空闪烁背景特效(Canvas 实现,星星数量/闪烁速度可调)

CANVASJS 许可:自研原创

星空闪烁 Canvas 背景:自研星星闪烁 + 柔和光晕动画,数量、闪烁速度、颜色实时可调,高分屏清晰不模糊,纯原生 Canvas 零依赖。

效果演示(真实可交互)

完整代码

<canvas id="stars" style="width:100%;height:320px;"></canvas>
const canvas = document.getElementById('stars');
const ctx = canvas.getContext('2d');
let W, H, stars = [];
const cfg = { count: 180, speed: 8, color: '#ffffff' };

function resize() {
  const r = canvas.getBoundingClientRect();
  const dpr = window.devicePixelRatio || 1;
  W = canvas.width = r.width * dpr;
  H = canvas.height = r.height * dpr;
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function init() {
  stars = [];
  for (let i = 0; i < cfg.count; i++) {
    stars.push({
      x: Math.random() * W,
      y: Math.random() * H,
      r: Math.random() * 1.5 + 0.4,
      base: Math.random() * 0.7 + 0.3,
      phase: Math.random() * Math.PI * 2,
      freq: Math.random() * 1.6 + 0.4,
      drift: (Math.random() - .5) * 0.15,
    });
  }
}
let t = 0;
function step() {
  t += 0.016;
  ctx.clearRect(0, 0, W, H);
  for (const s of stars) {
    s.x += s.drift;
    if (s.x > W) s.x = 0;
    if (s.x < 0) s.x = W;
    const tw = 0.35 + 0.65 * (0.5 + 0.5 * Math.sin(t * s.freq * 2.2 + s.phase));
    const alpha = s.base * tw;
    if (s.r > 1.15) {
      ctx.beginPath();
      ctx.arc(s.x, s.y, s.r * 3.2, 0, Math.PI * 2);
      ctx.fillStyle = cfg.color;
      ctx.globalAlpha = alpha * 0.18;
      ctx.fill();
    }
    ctx.beginPath();
    ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2);
    ctx.fillStyle = cfg.color;
    ctx.globalAlpha = alpha;
    ctx.fill();
  }
  ctx.globalAlpha = 1;
  requestAnimationFrame(step);
}
resize(); init(); step();
window.addEventListener('resize', () => { resize(); init(); });
canvas {
  background: radial-gradient(ellipse at 50% 30%, #1b2340 0%, #0c1020 60%, #070a14 100%);
}

参数说明

参数位置说明
星星数量cfg.count40-400,数量越多画面越密,性能开销线性增长
闪烁速度cfg.speed / s.freq正弦频率系数,决定星星明暗变化的快慢
星星颜色cfg.color所有星星的统一颜色,可换成品牌色或暖黄色
星星大小s.r = Math.random()*1.5+0.4半径范围,>1.15 的星星额外绘制柔和光晕
横向漂移s.drift微小的水平漂移速度,模拟真实星空的缓慢移动

兼容性与性能

常见问题

Q: 和那些动辄几十 KB 的星空库有什么区别? 本组件是粤喵自研的原生实现,核心代码约 50 行,无依赖、无配置项学习成本;而第三方库通常附带大量用不到的 API,体积是我们的几十倍。

Q: 想让星星变成彩色怎么办? 修改 cfg.color 为单一颜色即可;想要每颗星颜色不同,把 cfg.color 替换成一个调色板数组,在 init() 里为每颗星星随机取色。

Q: 可以做流星效果吗? 可以。在 stars 数组中定期插入一个「流星」对象(高速度、拖尾),绘制时沿运动方向画一条渐隐的线段即可,参考上方代码结构自行扩展。

Q: 可以商用吗? 可以。本组件为粤喵自研原创,免费商用无需署名;也欢迎在评论区分享你的魔改版本。

常见问题

这个组件可以商用吗?

可以。本组件为粤喵自研原创,可免费用于个人和商业项目,无需署名。

浏览器兼容性如何?

支持所有现代浏览器(Chrome / Firefox / Safari / Edge 最新版本)。旧版 IE 不支持 CSS 动画相关特性。

怎么修改动画参数?

直接调整 CSS 中的 animation-duration(时长)、animation-timing-function(缓动曲线)等属性即可,代码中有注释说明。