首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

js粒子效果代码

以下是一个使用 JavaScript 和 Canvas 实现简单粒子效果的示例代码:

代码语言:txt
复制
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      margin: 0;
      overflow: hidden;
      background-color: #000;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>

  <script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    window.addEventListener('resize', () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    });

    // 粒子类
    class Particle {
      constructor(x, y) {
        this.x = x;
        this.y = y;
        this.vx = Math.random() * 2 - 1;
        this.vy = Math.random() * 2 - 1;
        this.radius = Math.random() * 3 + 1;
        this.color = `rgba(255, 255, 255, ${Math.random()})`;
      }

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

      update() {
        this.x += this.vx;
        this.y += this.vy;

        if (this.x > canvas.width || this.x < 0) {
          this.vx = -this.vx;
        }
        if (this.y > canvas.height || this.y < 0) {
          this.vy = -this.vy;
        }

        this.draw();
      }
    }

    const particles = [];

    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 => particle.update());
      requestAnimationFrame(animate);
    }

    animate();
  </script>
</body>

</html>

基础概念

  • Canvas:HTML5 提供的一个用于绘制图形的区域。
  • 粒子系统:由大量微小的粒子组成的系统,用于模拟各种自然现象和视觉效果。

优势

  • 可以实现非常绚丽、动态和个性化的视觉效果。
  • 对硬件资源的需求相对较低,在大多数设备上都能流畅运行。

应用场景

  • 背景特效,如星空闪烁、烟雾弥漫。
  • 游戏中的特效,如魔法光芒、爆炸碎片。
  • 网站的加载动画或装饰性元素。

可能遇到的问题及解决方法

  • 粒子运动不流畅:可能是帧率过低,可以优化代码逻辑或减少粒子数量。
  • 粒子重叠或堆积:调整粒子的速度和初始位置生成逻辑。
  • 不同浏览器兼容性问题:进行充分的跨浏览器测试,并根据不同浏览器做适当调整。
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券