中文
Click & feedback · Vanilla JS + CSS

Confetti burst

彩纸礼花爆开

Burst a handful of confetti from a button.

Also searched as: 点一下按钮喷出彩纸, 完成时撒花庆祝, 提交成功放礼花, 彩带爆开

AI Markdown (.md)
Placement
Button
Mood
Playful, Dramatic
Trigger
点击
Site types
个人网站, 作品集, 工具站

How it works & accessibility

Each piece is a small element with one animation whose keyframes come from a projectile formula, so there is no canvas and every animation can be inspected; the layer is removed when the pieces land, and with reduced motion nothing is drawn.

Best for: Button (点击).

Reduced motion: 什么都不画(不建彩纸层、不播动画);按钮自己用文字或颜色的变化表示"完成了"

Mobile & touch: 手机上由调用方把 count 设成一半(18):实现不看屏幕大小,不会自己减半;页面上同时最多 300 片(maxParticles),狂点也不会把页面卡死

Key parameters

ParameterKeyDefaultRangeNotes
每片飞多久duration1600ms——
扩散的角度spread70°——
喷出的力度power700px/s——
飞完时落在起点下方多远fall260px——

Ready-to-paste AI prompt

Add “Confetti burst” to the button in my project: Each piece is a small element with one animation whose keyframes come from a projectile formula, so there is no canvas and every animation can be inspected; the layer is removed when the pieces land, and with reduced motion nothing is drawn.
Parameters: duration: 1600ms, spread: 70°, power: 700px/s, fall: 260px.
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/confetti-burst.md (canonical specification and reference code).

Dependency-free reference code

CSS
/* 彩纸礼花爆开的基本样式,配合 confetti-burst.js:彩纸层盖在页面上、不挡点击;彩纸片是一个小长方形,位置和旋转由动画给。
   放在 document.body 里的层是 fixed(用视口坐标);放在别的容器里的层(.cf-local)是 absolute、盖满容器并裁掉伸出去的部分——容器要有定位。 */
.cf-layer {
  position: fixed;
  inset: 0;
  z-index: 9999;
  overflow: hidden;
  pointer-events: none;
}
.cf-layer.cf-local {
  position: absolute;
  z-index: 5;
}
.cf-piece {
  position: absolute;
  width: 8px;
  height: 12px;
  margin: -6px 0 0 -4px;
  border-radius: 2px;
  will-change: transform, opacity;
}
JavaScript
// 彩纸礼花爆开(Confetti burst)· 原生 JS,不依赖任何库。
// 参考 StyleKit 的 confetti-burst、Animation Handbook 的 success-confetti 的做法(都是 MIT),自己实现,没有复制代码:
// 从一个元素(或一个点)喷出一把彩纸,朝上散开、边飞边转、受重力落下、淡出,飞完以后整层拿掉。
// 不用 canvas:每片彩纸是一个 <i class="cf-piece">,恰好一个 WAAPI 动画(位移、旋转、透明度写在同一组关键帧里),
// 关键帧按物理公式算好:方向 = 正上方加上 [-spread/2, spread/2] 里的随机角度,初速度在 [0.6, 1] × power 里随机,
// x(t) = vx·t,y(t) = vy·t + ½·g·t²,g 取到"飞完(t = T)时正好落在起点下方 fall 处";飞完时总共转 ±(360–1080)°;
// 前 70% 的时间不透明,后 30% 线性降到 0。
// 用法:const burst = confettiBurst(按钮元素, { container: 按钮所在的有定位的容器 }); burst.cancel() 立刻中止并拿掉,burst.finished 是飞完或取消后 resolve 的 Promise。
// origin:一个元素(从它的中心喷出)或一个点 { x, y }(视口坐标)。
// 选项(和数据里一样的数:spread 是度数、power 是 px/s、duration 和 fall 是 ms 和 px):
//   duration 每片飞多久(默认 1600);spread 扩散的总角度,以正上方为中心张开这么大(默认 70);power 喷出的最大初速度(默认 700);
//   fall 飞完时落在起点下方多远(默认 260);count 片数(默认 36,手机上由调用方设成一半:实现不看屏幕大小);colors 颜色数组;
//   random 随机数函数,默认 Math.random(传一个固定种子的,每次结果一样);
//   container 放彩纸层的元素,默认 document.body(彩纸层 position: fixed、用视口坐标);传了别的元素时彩纸层是它里面的 position: absolute、
//   坐标相对它,彩纸不会飞出它(它要有定位:position 不是 static);
//   maxParticles 页面上同时最多这么多片(默认 300),再喷会超出时这一次什么都不做;ignoreReducedMotion 只给"用户主动点播放"的演示用。
// 彩纸层 aria-hidden、pointer-events: none,不挡点击;开启"减少动态"时什么都不画(不建彩纸层),返回的 finished 已经 resolve,
// 调用方自己用文字或颜色表示"完成了"。没有监听器、没有定时器;页面上的动画被外部全部取消时(比如暂停)不会报未处理的 Promise 拒绝,彩纸层照样拿掉。
// 页面上现在有几片彩纸在飞(所有彩纸层加起来,给 maxParticles 用)
let live = 0;

export function confettiBurst(origin, {
  duration = 1600,
  spread = 70,
  power = 700,
  fall = 260,
  count = 36,
  colors = ['#ff5a5f', '#ffb400', '#00a699', '#3b82f6', '#a855f7'],
  random = Math.random,
  container = document.body,
  maxParticles = 300,
  ignoreReducedMotion = false,
} = {}) {
  const nothing = { cancel() {}, finished: Promise.resolve() };
  if (!ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches) return nothing;
  if (live + count > maxParticles) return nothing;

  // 起点(彩纸层里的坐标):元素取中心;放在 body 上的层是 fixed,用视口坐标;放在别的容器里的层是 absolute,减掉容器的左上角
  const center = origin instanceof Element
    ? (({ left, top, width, height }) => ({ x: left + width / 2, y: top + height / 2 }))(origin.getBoundingClientRect())
    : origin;
  const local = container !== document.body;
  const box = local ? container.getBoundingClientRect() : { left: 0, top: 0 };
  // 彩纸层是 inset: 0,相对容器的内边距框(边框里面):容器有边框时再减掉边框的宽度
  const edge = local ? { x: container.clientLeft, y: container.clientTop } : { x: 0, y: 0 };
  const ox = center.x - box.left - edge.x;
  const oy = center.y - box.top - edge.y;

  const layer = document.createElement('div');
  layer.className = local ? 'cf-layer cf-local' : 'cf-layer';
  layer.setAttribute('aria-hidden', 'true');
  const T = duration / 1000;
  const STEPS = 20; // 每片 21 个关键帧(offset 每 0.05 一个:0.7 和 1 都正好落在关键帧上)
  const animations = [];
  for (let i = 0; i < count; i += 1) {
    const piece = document.createElement('i');
    piece.className = 'cf-piece';
    piece.style.left = `${ox}px`;
    piece.style.top = `${oy}px`;
    piece.style.background = colors[Math.floor(random() * colors.length) % colors.length];
    layer.append(piece);
    const angle = ((random() * 2 - 1) * spread * Math.PI) / 360; // 偏离正上方的角度(弧度):±spread/2
    const speed = power * (0.6 + 0.4 * random());
    const vx = speed * Math.sin(angle);
    const vy = -speed * Math.cos(angle); // 向下为正,往上喷是负的
    const g = (2 * (fall - vy * T)) / (T * T); // 飞完时正好落在起点下方 fall
    const turn = (360 + random() * 720) * (random() < 0.5 ? -1 : 1);
    const keyframes = [];
    for (let k = 0; k <= STEPS; k += 1) {
      const o = k / STEPS;
      const t = o * T;
      keyframes.push({
        offset: o,
        transform: `translate(${(vx * t).toFixed(2)}px, ${(vy * t + 0.5 * g * t * t).toFixed(2)}px) rotate(${(turn * o).toFixed(1)}deg)`,
        opacity: o <= 0.7 ? 1 : Math.max(0, 1 - (o - 0.7) / 0.3),
      });
    }
    animations.push(piece.animate(keyframes, { duration, easing: 'linear', fill: 'forwards' }));
  }
  container.append(layer);
  live += count;

  let done = false;
  let resolveFinished;
  const finished = new Promise((resolve) => { resolveFinished = resolve; });
  // 收尾:拿掉彩纸层、把片数还回去、resolve。飞完、cancel()、页面上的动画被外部全部取消都走这里,只做一次
  const finish = () => {
    if (done) return;
    done = true;
    layer.remove();
    live -= count;
    resolveFinished();
  };
  // allSettled:动画被取消时 finished 会拒绝,这里照样当成"完事了",不留未处理的拒绝
  Promise.allSettled(animations.map((a) => a.finished)).then(finish);
  return {
    cancel() {
      if (done) return;
      animations.forEach((a) => a.cancel());
      finish();
    },
    finished,
  };
}
HTML
<!-- 彩纸礼花爆开:按钮平时什么样就什么样,点的时候才从它中心喷出彩纸;彩纸盖在页面上、不挡点击 -->
<!-- 减少动态时彩纸什么都不画,所以按钮自己要用文字或颜色表示"完成了"(下面点完把文字改成"已完成") -->
<button type="button" id="done">完成</button>
<script type="module">
  import { confettiBurst } from './confetti-burst.js';
  const button = document.getElementById('done');
  button.addEventListener('click', () => {
    button.textContent = '已完成'; // 不依赖彩纸:没有彩纸(减少动态、脚本出错)时这句也在
    confettiBurst(button, { duration: 1600, spread: 70, power: 700, fall: 260 });
  });
</script>

More in Click & feedback

Browse all 86 effects →

Shown once per release · Always available in changelog