当前位置:首页 > JavaScript

js实现粒子特效

2026-01-30 23:37:42JavaScript

实现粒子特效的方法

使用JavaScript创建粒子特效可以通过Canvas或WebGL实现。以下是基于Canvas的简单粒子系统实现方法。

创建Canvas画布

在HTML中创建Canvas元素并获取2D渲染上下文:

js实现粒子特效

<canvas id="particleCanvas"></canvas>
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

定义粒子类

创建一个粒子类,包含位置、速度、大小等属性:

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = Math.random() * 5 + 1;
    this.speedX = Math.random() * 3 - 1.5;
    this.speedY = Math.random() * 3 - 1.5;
    this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
  }

  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    if (this.size > 0.2) this.size -= 0.1;
  }

  draw() {
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
    ctx.fill();
  }
}

管理粒子系统

创建粒子数组和动画循环:

js实现粒子特效

let particles = [];

function init() {
  for (let i = 0; i < 100; i++) {
    const x = Math.random() * canvas.width;
    const y = Math.random() * canvas.height;
    particles.push(new Particle(x, y));
  }
}

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  particles.forEach((particle, index) => {
    particle.update();
    particle.draw();
    if (particle.size <= 0.2) {
      particles.splice(index, 1);
    }
  });
  requestAnimationFrame(animate);
}

init();
animate();

添加交互效果

通过鼠标交互生成新粒子:

canvas.addEventListener('mousemove', (event) => {
  for (let i = 0; i < 5; i++) {
    particles.push(new Particle(event.x, event.y));
  }
});

优化性能

对于大量粒子,使用对象池技术复用粒子对象:

const particlePool = [];

function getParticle(x, y) {
  if (particlePool.length > 0) {
    const particle = particlePool.pop();
    particle.x = x;
    particle.y = y;
    particle.size = Math.random() * 5 + 1;
    return particle;
  }
  return new Particle(x, y);
}

function recycleParticle(particle) {
  particlePool.push(particle);
}

高级效果扩展

  1. 添加物理效果:实现重力、碰撞检测
  2. 纹理粒子:使用drawImage替代圆形绘制
  3. 粒子轨迹:减少clearRect的透明度实现拖尾效果
  4. 颜色渐变:动态改变粒子颜色
// 示例:重力效果
this.speedY += 0.1; // 在update方法中添加

以上方法提供了基础的粒子系统实现,可根据需求调整参数和扩展功能。对于更复杂的3D粒子效果,建议使用Three.js等WebGL库。

标签: 粒子特效
分享给朋友:

相关文章

vue实现边框特效

vue实现边框特效

Vue 实现边框特效的方法 边框特效可以通过 CSS 动画、伪元素、SVG 或 JavaScript 动态计算来实现。以下是几种常见的实现方式: 使用 CSS 动画实现动态边框 在 Vue 组件的…

vue跳页面实现特效

vue跳页面实现特效

Vue 页面跳转实现特效的方法 在 Vue 中实现页面跳转特效可以通过多种方式,以下是几种常见的方法: 使用 Vue Router 的过渡动画 Vue Router 与 Vue 的过渡系统结合,可以…

react实现特效

react实现特效

React 实现特效的常见方法 使用 CSS 动画和过渡 通过 CSS 的 @keyframes 和 transition 属性实现基础动画效果,结合 React 的 className 或 styl…

css制作跑车特效

css制作跑车特效

使用CSS制作跑车特效 跑车动画效果 通过CSS的@keyframes和transform属性可以实现跑车移动的动画效果。以下是一个简单的跑车移动动画代码示例: .car { position:…

css文字制作特效

css文字制作特效

文字阴影效果 使用 text-shadow 属性为文字添加阴影,支持多阴影叠加。参数依次为水平偏移、垂直偏移、模糊半径和颜色。 .text-shadow { text-shadow: 2px…

js实现水墨特效

js实现水墨特效

实现水墨特效的方法 水墨特效可以通过Canvas结合图像处理技术实现,以下是一种常见的实现方式: 使用Canvas处理图像 const canvas = document.createEl…