返回

JS 动画妙招:150 行代码搞定雪花飞舞特效

前端

当然可以,这是为你准备的文章。

如何像专业人士一样使用 JS 制作动画

前言

过去,我曾以为动画需要非常扎实的数学、物理基础。然而,最近的一次亲身经历彻底改变了我的想法——动画其实并不复杂。

在这篇文章中,我将分享我的经验,并带你一步步制作雪花飞舞特效。我们将使用 JavaScript 来实现这个效果,即使你没有动画基础,也能轻松上手。

1. 搭建画布

首先,我们需要创建一个画布,作为雪花飞舞的舞台。我们可以使用 HTML 的 canvas 元素来实现:

<canvas id="canvas" width="500" height="500"></canvas>

然后,我们需要通过 JavaScript 来获取这个画布元素:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

2. 创建雪花

接下来,我们需要创建一个雪花对象,来代表每个飘落的雪花。我们可以使用 ES6 的 class 语法来定义雪花类:

class Snowflake {
  constructor(x, y, radius) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.speedX = Math.random() * 5 - 2.5; // 随机生成雪花水平速度
    this.speedY = Math.random() * 5 + 2.5; // 随机生成雪花垂直速度
    this.rotation = Math.random() * 360; // 随机生成雪花旋转角度
    this.rotationSpeed = Math.random() * 0.1; // 随机生成雪花旋转速度
  }

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

  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    this.rotation += this.rotationSpeed;

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

3. 绘制雪花

现在,我们需要创建一个雪花列表,并不断地更新和绘制它们。我们可以在 main 函数中实现这个逻辑:

let snowflakes = [];

function main() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布

  for (let i = 0; i < snowflakes.length; i++) {
    const snowflake = snowflakes[i];
    snowflake.draw();
    snowflake.update();

    if (snowflake.y > canvas.height) {
      snowflakes.splice(i, 1); // 从列表中删除飞出屏幕的雪花
    }
  }

  requestAnimationFrame(main); // 循环调用 main 函数,实现动画效果
}

main();

4. 优化性能

为了提高动画的性能,我们可以通过以下几种方式进行优化:

  1. 限制雪花数量:我们可以限制同时显示的雪花数量,以减少渲染压力。
  2. 使用雪花的精灵图:我们可以将多个雪花放在一张精灵图上,然后只绘制一次精灵图,这样可以减少绘制次数。
  3. 使用缓存:我们可以将雪花的图像缓存在内存中,这样可以减少每次绘制雪花的开销。

结语

恭喜你,你已经成功地制作了一个雪花飞舞的动画效果!通过这篇教程,你不仅学会了制作雪花特效,还对 JS 动画的基本原理有了更深入的理解。希望你能继续探索动画的奥秘,创造出更多精彩的作品。