JSFiddle - React, Tailwind, and code Playground

by rolence0515

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>

<div style="margin-top:100px; margin-left:100px" id="animation"></div>

CSS

#animation {
  position: relative;
  width: 100px;
  height: 100px;
}

#animation div {
  position: absolute;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

JavaScript

class ConfettiAnimation {
    // 构造函数接收容器 ID 和粒子的配置选项
    constructor(containerId, particleCount = 30, particleSize = { min: 0, max: 1 }) {
        this.containerId = containerId; // 容器元素的 ID
        this.particleCount = particleCount; // 粒子数量
        this.particleSize = particleSize; // 粒子大小
        this.init(); // 初始化动画
    }

    // 初始化动画,创建粒子并启动动画
    init() {
        this.createParticles();
        this.startAnimation();
    }

    // 创建粒子元素并添加到容器中
    createParticles() {
        const container = document.getElementById(this.containerId);

        for (let i = 0; i < this.particleCount; i++) {
            const div = document.createElement('div');
            div.style.backgroundColor = `hsl(${Math.random() * 360}, 100%, 50%)`;
            container.appendChild(div);
        }
    }

    // 开始对粒子应用动画
    startAnimation() {
        anime.timeline({ loop: true })
        .add({
            targets: `#${this.containerId} div`,
            scale: [
                { value: this.particleSize.min, duration: 0 },
                { value: this.particleSize.max, duration: 1000 }
            ],
            opacity: [0.5, 1, 0],
            translateX: () => anime.random(-100, 100),
            translateY: [-400, 0],
            easing: "easeOutCubic",
            duration: 1000,
            delay: (el, i) => i * 100
        });
    }
}

// 使用示例
// 创建一个新的 ConfettiAnimation 实例
// 'animation' 是您的容器元素的 ID
// 粒子数设置为 30,大小范围从 0 到 1
const animation = new ConfettiAnimation('animation', 30, { min: 0, max: 1 });