当前位置:首页 > VUE

vue实现烟花

2026-01-08 02:59:34VUE

Vue 实现烟花效果

在 Vue 中实现烟花效果可以通过结合 CSS 动画和 JavaScript 动态生成烟花元素。以下是具体实现方法:

动态生成烟花元素

通过 Vue 的 v-for 动态生成烟花粒子,每个粒子代表烟花的一个火花。在模板中添加一个容器用于放置烟花:

<template>
  <div class="fireworks-container" @click="createFirework">
    <div 
      v-for="(particle, index) in particles" 
      :key="index"
      class="particle"
      :style="{
        left: particle.x + 'px',
        top: particle.y + 'px',
        backgroundColor: particle.color,
        transform: `scale(${particle.size})`
      }"
    ></div>
  </div>
</template>

烟花粒子数据与动画

在 Vue 的 data 中定义粒子数组,并通过方法生成随机粒子属性:

data() {
  return {
    particles: []
  }
},
methods: {
  createFirework(event) {
    const colors = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff'];
    const particleCount = 100;

    for (let i = 0; i < particleCount; i++) {
      const angle = Math.random() * Math.PI * 2;
      const speed = Math.random() * 5 + 2;
      const size = Math.random() * 0.5 + 0.5;

      this.particles.push({
        x: event.clientX,
        y: event.clientY,
        color: colors[Math.floor(Math.random() * colors.length)],
        size,
        vx: Math.cos(angle) * speed,
        vy: Math.sin(angle) * speed
      });
    }

    this.animateParticles();
  },
  animateParticles() {
    const animation = setInterval(() => {
      this.particles.forEach(particle => {
        particle.x += particle.vx;
        particle.y += particle.vy;
        particle.vy += 0.1; // 重力效果
        particle.size *= 0.99; // 粒子逐渐缩小
      });

      this.particles = this.particles.filter(p => p.size > 0.1);

      if (this.particles.length === 0) {
        clearInterval(animation);
      }
    }, 30);
  }
}

CSS 样式

为烟花粒子添加基础样式和动画效果:

.fireworks-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.particle {
  position: absolute;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  pointer-events: none;
  transition: transform 0.1s ease-out;
}

优化与扩展

  • 添加 requestAnimationFrame 替代 setInterval 以获得更流畅的动画性能。
  • 引入随机延迟和不同的粒子形状(如线条或星星)以增强视觉效果。
  • 通过 Vue 的 transition-group 实现粒子消失的渐隐效果。

完整示例可通过点击页面触发烟花爆炸,粒子会受重力影响下坠并逐渐消失。可根据需要调整粒子数量、颜色和运动参数以实现不同风格的烟花效果。

vue实现烟花

标签: 烟花vue
分享给朋友:

相关文章

vue里实现增删改查

vue里实现增删改查

在Vue中实现增删改查 数据初始化 在Vue组件的data中定义初始数据和表单绑定的变量: data() { return { items: [ { id: 1, name…

实现vue组件

实现vue组件

Vue 组件的基本实现 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种方式: 单文件组件 (SFC) 使用 .vue 文件格式,…

vue实现公告

vue实现公告

Vue 实现公告功能的方法 公告功能通常需要实现滚动展示、自动切换或固定显示的效果。以下是几种常见的实现方式: 使用 marquee 标签实现滚动公告 <template> <…

vue实现rtc

vue实现rtc

Vue 实现 RTC 的步骤 安装依赖 在 Vue 项目中安装 WebRTC 相关依赖,如 simple-peer 或 peerjs,用于简化 WebRTC 的实现。 运行以下命令安装 simple-…

vue 实现流程

vue 实现流程

Vue 实现流程 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是 Vue 实现的基本流程: 安装 Vue.js 通过 CDN 引入或使用 npm/yarn 安装:…

vue实现答辩

vue实现答辩

Vue 实现答辩系统的关键步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目,安装 Vue Router 管理路由,Pinia/Vuex 进行状态管理。配置 ESLint 和 Pre…