js如何实现粒子动画效果 Canvas打造炫酷粒子特效

来源:IT编程作者:北京网站建设头衔:草根站长
导读:本期聚焦于小伙伴创作的《js如何实现粒子动画效果 Canvas打造炫酷粒子特效》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《js如何实现粒子动画效果 Canvas打造炫酷粒子特效》有用,将其分享出去将是对创作者最好的鼓励。

粒子动画是前端常见的视觉特效,通过大量微小粒子的运动、变化组合出炫酷的视觉效果,Canvas配合JavaScript可以高效实现这类效果。下面我们一步步实现基础的粒子动画,再扩展交互功能。

js如何实现粒子动画效果 Canvas打造炫酷粒子特效

基础准备工作

首先需要在HTML中创建Canvas元素,设置合适的宽高,同时获取Canvas的上下文对象,后续所有绘制操作都基于这个上下文完成。

<canvas id="particleCanvas" width="800" height="600"></canvas>

对应的JavaScript初始化代码如下:

// 获取Canvas元素和上下文
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
// 设置Canvas宽高为窗口大小,避免拉伸
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

定义粒子类

每个粒子需要有独立的位置、速度、大小、颜色等属性,我们把这些属性和对应的更新、绘制方法封装到粒子类中。

class Particle {
  constructor() {
    // 粒子初始位置:随机分布在Canvas范围内
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height;
    // 粒子速度:x和y方向随机速度,范围在-1到1之间
    this.vx = (Math.random() - 0.5) * 2;
    this.vy = (Math.random() - 0.5) * 2;
    // 粒子大小:1到3像素之间随机
    this.size = Math.random() * 2 + 1;
    // 粒子颜色:随机生成浅色系颜色
    this.color = `rgba(${Math.random() * 100 + 155}, ${Math.random() * 100 + 155}, ${Math.random() * 100 + 155}, 0.8)`;
  }

  // 更新粒子位置
  update() {
    this.x += this.vx;
    this.y += this.vy;
    // 边界检测:粒子超出Canvas边界时从另一侧出现
    if (this.x > canvas.width) this.x = 0;
    if (this.x < 0) this.x = canvas.width;
    if (this.y > canvas.height) this.y = 0;
    if (this.y < 0) this.y = canvas.height;
  }

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

初始化粒子数组与动画循环

我们需要创建一定数量的粒子实例存入数组,然后通过requestAnimationFrame搭建动画循环,每一帧清空画布、更新粒子状态、绘制粒子。

// 粒子数量,可根据性能调整
const particleCount = 150;
const particles = [];

// 初始化粒子数组
for (let i = 0; i < particleCount; i++) {
  particles.push(new Particle());
}

// 动画循环函数
function animate() {
  // 清空画布,设置半透明黑色背景实现拖尾效果
  ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 遍历所有粒子,更新并绘制
  particles.forEach(particle => {
    particle.update();
    particle.draw();
  });

  // 请求下一帧动画
  requestAnimationFrame(animate);
}

// 启动动画
animate();

添加粒子连线效果

为了让粒子效果更炫酷,我们可以给距离较近的粒子之间添加连线,增强整体联动感。首先需要计算粒子之间的距离,当距离小于阈值时绘制连线。

// 连线距离阈值
const connectionDistance = 100;

// 更新animate函数中的绘制逻辑,添加连线处理
function animate() {
  ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 先更新所有粒子的位置
  particles.forEach(particle => {
    particle.update();
  });

  // 遍历粒子,绘制连线和粒子
  for (let i = 0; i < particles.length; i++) {
    const p1 = particles[i];
    p1.draw();

    // 和后续粒子对比距离,避免重复绘制连线
    for (let j = i + 1; j < particles.length; j++) {
      const p2 = particles[j];
      const dx = p1.x - p2.x;
      const dy = p1.y - p2.y;
      const distance = Math.sqrt(dx * dx + dy * dy);

      // 距离小于阈值时绘制连线
      if (distance < connectionDistance) {
        // 连线透明度随距离增大而减小
        const opacity = 1 - distance / connectionDistance;
        ctx.beginPath();
        ctx.strokeStyle = `rgba(255, 255, 255, ${opacity * 0.5})`;
        ctx.lineWidth = 0.5;
        ctx.moveTo(p1.x, p1.y);
        ctx.lineTo(p2.x, p2.y);
        ctx.stroke();
      }
    }
  }

  requestAnimationFrame(animate);
}

添加鼠标交互效果

还可以给粒子动画添加鼠标交互,当鼠标移动时,附近的粒子会被吸引或者避让,提升用户参与感。我们通过监听鼠标移动事件,获取鼠标位置,然后修改附近粒子的速度方向。

// 鼠标位置对象
const mouse = {
  x: null,
  y: null
};

// 监听鼠标移动事件
canvas.addEventListener('mousemove', (e) => {
  mouse.x = e.clientX;
  mouse.y = e.clientY;
});

// 鼠标离开Canvas时清空位置
canvas.addEventListener('mouseout', () => {
  mouse.x = null;
  mouse.y = null;
});

// 修改Particle类的update方法,添加鼠标交互逻辑
update() {
  // 鼠标存在时处理交互
  if (mouse.x !== null && mouse.y !== null) {
    const dx = mouse.x - this.x;
    const dy = mouse.y - this.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    // 鼠标影响范围
    const mouseRadius = 150;
    if (distance < mouseRadius) {
      // 粒子被鼠标排斥,速度方向远离鼠标
      const force = (mouseRadius - distance) / mouseRadius;
      this.vx -= (dx / distance) * force * 0.5;
      this.vy -= (dy / distance) * force * 0.5;
    }
  }

  this.x += this.vx;
  this.y += this.vy;
  // 速度衰减,避免粒子速度过快
  this.vx *= 0.99;
  this.vy *= 0.99;

  // 边界检测
  if (this.x > canvas.width) this.x = 0;
  if (this.x < 0) this.x = canvas.width;
  if (this.y > canvas.height) this.y = 0;
  if (this.y < 0) this.y = canvas.height;
}

参数调整建议

你可以通过调整以下参数获得不同的粒子效果:

  • 修改particleCount调整粒子数量,数量越多效果越密集,但性能消耗越高
  • 调整粒子类的vxvy范围,改变粒子运动速度
  • 修改connectionDistance调整连线触发距离,改变连线密集程度
  • 调整鼠标影响的mouseRadius和排斥力度,改变交互效果强度

Canvasparticle_animationJavaScriptrequestAnimationFrame修改时间:2026-06-19 11:51:26

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。