点击爆彩球:鼠标点击炸开一串彩色小球

鼠标点一下,点击位置炸出一串彩色小球,四散飞开再慢慢消失;按住不放会越攒越多,松手一次性爆开一大片。是个人站点很讨喜的一个小互动。纯原生 JS + canvas,不用引任何库。下面每块都能点「预览效果」直接看——在预览里点一下、长按一下就能看到效果。

原版 · canvas 点击特效

HTML点击爆彩球 · 原版
<style>
.demo-zone{padding:70px 20px;text-align:center;background:#fff;
  font:14px/1.9 sans-serif;color:#4a5568;min-height:240px;cursor:pointer}
.demo-zone h3{margin:0 0 8px;font-size:16px;color:#2d3748}
</style>

<div class="demo-zone">
  <h3>在这里点击 / 长按 →</h3>
  <p>单击炸出一小簇,按住不放越攒越多,松手时一次性爆开。</p>
</div>

<script>
function clickEffect() {
        let balls = [];
        let longPressed = false;
        let longPress;
        let multiplier = 0;
        let width, height;
        let origin;
        let normal;
        let ctx;
        const colours = ["#F73859", "#14FFEC", "#00E0FF", "#FF99FE", "#FAF15D"];
        const canvas = document.createElement("canvas");
        document.body.appendChild(canvas);
        canvas.setAttribute("style", "width: 100%; height: 100%; top: 0; left: 0; z-index: 99999; position: fixed; pointer-events: none;");
        const pointer = document.createElement("span");
        pointer.classList.add("pointer");
        document.body.appendChild(pointer);

        if (canvas.getContext && window.addEventListener) {
            ctx = canvas.getContext("2d");
            updateSize();
            window.addEventListener('resize', updateSize, false);
            loop();
            window.addEventListener("mousedown", function(e) {
                pushBalls(randBetween(10, 0), e.clientX, e.clientY);
                document.body.classList.add("is-pressed");
                longPress = setTimeout(function() {
                    document.body.classList.add("is-longpress");
                    longPressed = true;
                }, 500);
            }, false);
            window.addEventListener("mouseup", function(e) {
                clearInterval(longPress);
                if (longPressed == true) {
                    document.body.classList.remove("is-longpress");
                    pushBalls(randBetween(50 + Math.ceil(multiplier), 100 + Math.ceil(multiplier)), e.clientX, e.clientY);
                    longPressed = false;
                }
                document.body.classList.remove("is-pressed");
            }, false);
            window.addEventListener("mousemove", function(e) {
                let x = e.clientX;
                let y = e.clientY;
                pointer.style.top = y + "px";
                pointer.style.left = x + "px";
            }, false);
        } else {
            console.log("canvas or addEventListener is unsupported!");
        }


        function updateSize() {
            canvas.width = window.innerWidth * 2;
            canvas.height = window.innerHeight * 2;
            canvas.style.width = window.innerWidth + 'px';
            canvas.style.height = window.innerHeight + 'px';
            ctx.scale(2, 2);
            width = (canvas.width = window.innerWidth);
            height = (canvas.height = window.innerHeight);
            origin = { x: width / 2, y: height / 2 };
            normal = { x: width / 2, y: height / 2 };
        }
        class Ball {
            constructor(x = origin.x, y = origin.y) {
                this.x = x;
                this.y = y;
                this.angle = Math.PI * 2 * Math.random();
                if (longPressed == true) {
                    this.multiplier = randBetween(14 + multiplier, 15 + multiplier);
                } else {
                    this.multiplier = randBetween(6, 12);
                }
                this.vx = (this.multiplier + Math.random() * 0.5) * Math.cos(this.angle);
                this.vy = (this.multiplier + Math.random() * 0.5) * Math.sin(this.angle);
                this.r = randBetween(8, 12) + 3 * Math.random();
                this.color = colours[Math.floor(Math.random() * colours.length)];
            }
            update() {
                this.x += this.vx - normal.x;
                this.y += this.vy - normal.y;
                normal.x = -2 / window.innerWidth * Math.sin(this.angle);
                normal.y = -2 / window.innerHeight * Math.cos(this.angle);
                this.r -= 0.3;
                this.vx *= 0.9;
                this.vy *= 0.9;
            }
        }

        function pushBalls(count = 1, x = origin.x, y = origin.y) {
            for (let i = 0; i < count; i++) {
                balls.push(new Ball(x, y));
            }
        }

        function randBetween(min, max) {
            return Math.floor(Math.random() * max) + min;
        }

        function loop() {
            ctx.fillStyle = "rgba(255, 255, 255, 0)";
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            for (let i = 0; i < balls.length; i++) {
                let b = balls[i];
                if (b.r < 0) continue;
                ctx.fillStyle = b.color;
                ctx.beginPath();
                ctx.arc(b.x, b.y, b.r, 0, Math.PI * 2, false);
                ctx.fill();
                b.update();
            }
            if (longPressed == true) {
                multiplier += 0.2;
            } else if (!longPressed && multiplier >= 0) {
                multiplier -= 0.4;
            }
            removeBall();
            requestAnimationFrame(loop);
        }

        function removeBall() {
            for (let i = 0; i < balls.length; i++) {
                let b = balls[i];
                if (b.x + b.r < 0 || b.x - b.r > width || b.y + b.r < 0 || b.y - b.r > height || b.r < 0) {
                    balls.splice(i, 1);
                }
            }
        }
    }
    clickEffect();
</script>

效果没问题,但代码里有几处会实际影响表现,我逐个验证过。

① randBetween 的公式写错了

```js

function randBetween(min, max) { return Math.floor(Math.random() * max) + min; }

```

正确公式应该是 Math.floor(Math.random() * (max - min)) + min,括号位置错了。实际取值范围是 min ~ min+max-1,我采样了几次:

调用 期望 实际采样
randBetween(10, 0) 0 ~ 10 10, 10, 10, 10, 10
randBetween(8, 12) 8 ~ 12 10, 10, 19, 19, 15
randBetween(6, 12) 6 ~ 12 6, 14, 14, 14, 16

影响两处:

  • 单击 pushBalls(randBetween(10, 0)):因为 max 是 0,恒等于 10,所谓"随机"根本没随机。
  • 长按 randBetween(50+multiplier, 100+multiplier):multiplier=20 时期望 70~120,实测能到 163,超出上限不少。长按越久球越多(这是设计意图),但涨得比预期快。

② 高清屏适配做了,但被自己后面一行覆盖掉了

```js

canvas.width = window.innerWidth * 2; // 按 2 倍设画布

ctx.scale(2, 2); // 缩放 2 倍

...

width = (canvas.width = window.innerWidth); // ← 又把 width 设回 1 倍

```

给 canvas.width 赋值会重置整个绘图上下文,包括之前设的 scale。我实测了 ctx.getTransform().a:

时机 transform.a
ctx.scale(2,2) 之后 2
重设 canvas.width 之后 1

也就是说高清适配白做了——在高分屏(Retina、大多数手机)上圆点边缘会发虚。

③ setTimeout 配 clearInterval

```js

longPress = setTimeout(...);

...

clearInterval(longPress);

```

clearInterval 和 clearTimeout 在多数浏览器里能互换(定时器 ID 共用一套),但规范上没保证,应该用配套的 clearTimeout。

④ removeBall 在正序遍历里 splice 会漏删

```js

for (let i = 0; i < balls.length; i++) {

if (...) { balls.splice(i, 1); } // 删完 i 位置后,后面的元素前移,i++ 会跳过下一个

}

```

splice 删掉第 i 个后,原本第 i+1 个移到第 i 位,而循环继续 i++,这个元素就被跳过了。它会在下一帧再被检查(所以不会永久残留),但清理不够及时。正序遍历 + splice 应当倒序,这是标准写法。

⑤ 其他

  • 只监听鼠标事件:手机上完全没效果,得补 touchstart / touchend。
  • multiplier 只增不减到负数:有 multiplier >= 0 的判断,但没有下限保护到 0 以下时会一直减(else if (!longPressed && multiplier >= 0) multiplier -= 0.4 这个条件其实保证了不会变负,OK)。
  • 创建了 pointer 这个 span 但没给任何样式:原版有 .pointer 类,却没定义 CSS,等于多了个看不见的空元素。
  • 没有 prefers-reduced-motion 处理。

修复版 · 修掉上面这些问题

HTML点击爆彩球 · 修复版
<style>
.demo-zone2{padding:70px 20px;text-align:center;background:#fff;
  font:14px/1.9 sans-serif;color:#4a5568;min-height:240px;cursor:pointer}
.demo-zone2 h3{margin:0 0 8px;font-size:16px;color:#2d3748}
</style>

<div class="demo-zone2">
  <h3>在这里点击 / 长按 →</h3>
  <p>单击随机 0~10 个(真的随机了),长按最多 120 个,松手爆开。</p>
</div>

<script>
(function () {
  'use strict';

  // 尊重系统的"减少动态效果"设置
  if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { return; }

  var canvas = document.createElement('canvas');
  if (!canvas.getContext) { return; }
  canvas.style.cssText = 'width:100%;height:100%;top:0;left:0;position:fixed;pointer-events:none;z-index:99999';
  document.body.appendChild(canvas);

  var ctx = canvas.getContext('2d');
  var dpr = window.devicePixelRatio || 1;
  var W = 0, H = 0;

  function updateSize() {
    W = window.innerWidth;
    H = window.innerHeight;
    // 按 dpr 放大画布后统一缩放,高分屏不发虚
    canvas.width  = W * dpr;
    canvas.height = H * dpr;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  }
  updateSize();

  var colours = ['#F73859', '#14FFEC', '#00E0FF', '#FF99FE', '#FAF15D'];
  var balls = [];
  var MAX_BALLS = 300;          // 上限,防止长按攒爆
  var longPressed = false;
  var longPressTimer = null;
  var multiplier = 0;

  // 修正:Math.random() * (max - min) + min
  function randBetween(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }

  function Ball(x, y) {
    this.x = x; this.y = y;
    this.angle = Math.PI * 2 * Math.random();
    var m = longPressed
      ? randBetween(14 + multiplier, 15 + multiplier)
      : randBetween(6, 12);
    this.vx = (m + Math.random() * 0.5) * Math.cos(this.angle);
    this.vy = (m + Math.random() * 0.5) * Math.sin(this.angle);
    this.r = randBetween(8, 12) + 3 * Math.random();
    this.color = colours[Math.floor(Math.random() * colours.length)];
  }
  Ball.prototype.update = function () {
    this.x += this.vx;
    this.y += this.vy;
    this.r -= 0.3;
    this.vx *= 0.9;
    this.vy *= 0.9;
  };

  function pushBalls(count, x, y) {
    for (var i = 0; i < count; i++) {
      if (balls.length >= MAX_BALLS) { return; }
      balls.push(new Ball(x, y));
    }
  }

  function loop() {
    ctx.clearRect(0, 0, W, H);
    // 倒序遍历:配合 splice 不会漏删
    for (var i = balls.length - 1; i >= 0; i--) {
      var b = balls[i];
      if (b.r < 0 ||
          b.x + b.r < 0 || b.x - b.r > W ||
          b.y + b.r < 0 || b.y - b.r > H) {
        balls.splice(i, 1);
        continue;
      }
      ctx.fillStyle = b.color;
      ctx.beginPath();
      ctx.arc(b.x, b.y, b.r, 0, Math.PI * 2, false);
      ctx.fill();
      b.update();
    }
    if (longPressed) {
      multiplier += 0.2;
      if (multiplier > 30) { multiplier = 30; }   // 封顶
    } else if (multiplier > 0) {
      multiplier = Math.max(0, multiplier - 0.4);
    }
    requestAnimationFrame(loop);
  }

  function startPress(x, y) {
    pushBalls(randBetween(0, 10), x, y);   // 真正的 0~10 随机
    longPressTimer = setTimeout(function () {
      longPressed = true;
    }, 500);
  }
  function endPress(x, y) {
    clearTimeout(longPressTimer);          // setTimeout 配 clearTimeout
    if (longPressed) {
      var n = randBetween(50, 100) + Math.ceil(multiplier);
      if (n > 120) { n = 120; }            // 封顶,避免一次爆太多
      pushBalls(n, x, y);
      longPressed = false;
    }
    multiplier = 0;
  }

  window.addEventListener('mousedown', function (e) { startPress(e.clientX, e.clientY); });
  window.addEventListener('mouseup',   function (e) { endPress(e.clientX, e.clientY); });
  // 补上触摸支持,手机也能玩
  window.addEventListener('touchstart', function (e) {
    var t = e.touches[0];
    if (t) { startPress(t.clientX, t.clientY); }
  }, { passive: true });
  window.addEventListener('touchend', function (e) {
    var t = e.changedTouches[0];
    endPress(t ? t.clientX : W / 2, t ? t.clientY : H / 2);
  }, { passive: true });
  window.addEventListener('resize', updateSize);

  loop();
})();
</script>

改了这些,实测确认:

  • randBetween 公式修正:单击现在真的是 0~10 随机(原来恒为 10)。
  • 高清适配真正生效:setTransform 在设完 width 之后调用(原版是先 scale 再重设 width,顺序反了),高分屏圆点不发虚。
  • clearTimeout 配套。
  • 倒序 splice:不再漏删。
  • 加了数量上限 300 和 multiplier 封顶 30,长按不会攒爆。
  • 补触摸事件,手机可用。
  • 加 prefers-reduced-motion:系统开了减少动效就直接不启用。
  • 去掉了那个没有样式的 pointer 空元素。

柔和版 · 小球带拖尾且渐隐

球在飞的过程中逐渐变淡,并留一点拖尾,比纯色块柔和。

HTML点击爆彩球 · 柔和渐隐版
<style>
.demo-zone3{padding:70px 20px;text-align:center;background:#fff;
  font:14px/1.9 sans-serif;color:#4a5568;min-height:240px;cursor:pointer}
.demo-zone3 h3{margin:0 0 8px;font-size:16px;color:#2d3748}
</style>

<div class="demo-zone3">
  <h3>在这里点击 / 长按 →</h3>
  <p>球在飞的时候会慢慢变透明,尾巴带一层柔光。</p>
</div>

<script>
(function () {
  'use strict';
  if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { return; }

  var canvas = document.createElement('canvas');
  if (!canvas.getContext) { return; }
  canvas.style.cssText = 'width:100%;height:100%;top:0;left:0;position:fixed;pointer-events:none;z-index:99999';
  document.body.appendChild(canvas);
  var ctx = canvas.getContext('2d');
  var dpr = window.devicePixelRatio || 1, W = 0, H = 0;

  function updateSize() {
    W = window.innerWidth; H = window.innerHeight;
    canvas.width = W * dpr; canvas.height = H * dpr;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  }
  updateSize();

  var colours = ['#5b7cfa', '#9f7aea', '#f56565', '#38a169', '#ecc94b'];
  var balls = [];

  function rand(a, b) { return Math.floor(Math.random() * (b - a)) + a; }

  function Ball(x, y) {
    this.x = x; this.y = y;
    var a = Math.PI * 2 * Math.random();
    var sp = 1.5 + Math.random() * 3;
    this.vx = Math.cos(a) * sp;
    this.vy = Math.sin(a) * sp;
    this.r = rand(5, 11);
    this.life = 1;
    this.color = colours[rand(0, colours.length)];
  }

  function burst(count, x, y) {
    for (var i = 0; i < count && balls.length < 400; i++) { balls.push(new Ball(x, y)); }
  }

  function loop() {
    ctx.clearRect(0, 0, W, H);
    for (var i = balls.length - 1; i >= 0; i--) {
      var b = balls[i];
      b.x += b.vx; b.y += b.vy;
      b.vx *= 0.96; b.vy *= 0.96;
      b.life -= 0.016;
      if (b.life <= 0) { balls.splice(i, 1); continue; }
      ctx.globalAlpha = b.life;
      ctx.fillStyle = b.color;
      ctx.beginPath();
      ctx.arc(b.x, b.y, b.r * (0.4 + 0.6 * b.life), 0, Math.PI * 2);
      ctx.fill();
      // 外层柔光
      ctx.globalAlpha = b.life * 0.25;
      ctx.beginPath();
      ctx.arc(b.x, b.y, b.r * 1.9, 0, Math.PI * 2);
      ctx.fill();
    }
    ctx.globalAlpha = 1;
    requestAnimationFrame(loop);
  }

  window.addEventListener('mousedown', function (e) { burst(18, e.clientX, e.clientY); });
  window.addEventListener('touchstart', function (e) {
    var t = e.touches[0]; if (t) { burst(18, t.clientX, t.clientY); }
  }, { passive: true });
  window.addEventListener('resize', updateSize);

  loop();
})();
</script>

这版去掉了长按逻辑,改成单击就爆 18 个,更直接。视觉上两层:中心实心圆 + 外层半透明光晕,配合 globalAlpha 渐隐。

改的时候注意这几点

  • 改颜色动 colours 数组:加色减色随意,随机取一个。
  • 改"炸开多少":修复版单击是 randBetween(0, 10),长按是 randBetween(50,100) + multiplier 且封顶 120。想更热闹就调大,但别贪多——一次几百个球在低端机上会掉帧。
  • 改快慢:b.r -= 0.3 控制缩小速度(值越小活得越久);vx *= 0.9 控制减速(越接近 1 飞得越远)。
  • 一定要留数量上限:没有上限的话长按几秒钟能攒上千个球,requestAnimationFrame 每帧要画上千次,页面直接卡死。
  • pointer-events:none 别删:canvas 是全屏 fixed 且 z-index 很高,不加这行会挡住整页的点击,站点直接不可用了。
  • z-index 跟你的悬浮条冲突就往下调:99999 如果被返回顶部按钮之类的盖住,改成小一点。
  • 倒序 splice 是必须的习惯:正序遍历数组时 splice 会跳过元素,所有"边遍历边删"的场景都应该倒序。
  • canvas.width 赋值会重置上下文:设完宽高后再调 scale / setTransform,顺序反了就白做。

怎么用

代码块整段粘进 WordPress 的「自定义 HTML」区块即可(纯原生 JS,不依赖 jQuery)。想全站生效,把 <script> 那段放进主题的 footer.php 或子主题的 JS 文件里。

兼容性

canvas、requestAnimationFrame、class / let 语法在 Chrome / Edge / Firefox / Safari 全系支持。触摸事件在移动端正常触发。微信内置浏览器可用,但部分安卓机上长按会优先触发系统的"复制/保存图片"菜单。


代码仅供学习交流,禁止商用。更多网站美化代码,前往 维形筑网 www.wxzcw.com。

作者:Flechazo

如若转载,请注明出处:维形筑网 https://wxzcw.com

赞 (0)
复制提醒弹窗:复制时提示保留原文链接
上一篇 2026年10月29日 上午11:36
打字粒子特效:输入框打字时炸出彩色碎屑
下一篇 2026年10月29日 上午11:41

相关推荐

维 形 筑 网