返回

轻松入门Canvas线条动画——动起来更直观!

前端

前言

先上效果图,相信大家在很多地方见过这种线条动画。
尽管样式稍有不同,但总体来说是一致的。原作者是谁不得而知,效果还是挺炫酷的。话不多说,开始制作。

正文

我们将使用TypeScript进行开发(自己的ts练习项目),采用live-server作为开发服务器,一切从简。即使没有TypeScript的基础也不用担心。因为ts代码很少,不影响理解。

1. 项目搭建

新建项目文件夹,用记事本或编辑器创建index.html文件,在其中添加以下内容:

<!DOCTYPE html>
<html>
<head>
  
</head>
<body>
  <canvas id="canvas" width="600" height="600"></canvas>
  <script src="main.js"></script>
</body>
</html>

然后在项目文件夹下创建一个名为main.js的文件,在其中添加以下内容:

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

// 创建一个新的线条动画
const animation = new LineAnimation(canvas, ctx);

// 开始动画
animation.start();

2. 创建线条动画

在main.js文件中,添加以下代码来创建线条动画:

class LineAnimation {
  constructor(canvas, ctx) {
    this.canvas = canvas;
    this.ctx = ctx;

    this.lines = []; // 保存所有线条
    this.interval = null; // 用于控制动画的间隔
  }

  start() {
    // 每隔10毫秒创建一个新的线条
    this.interval = setInterval(() => {
      this.lines.push(new Line(this.canvas, this.ctx));
    }, 10);
  }

  stop() {
    // 清除动画间隔
    clearInterval(this.interval);
  }

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

    // 绘制所有线条
    this.lines.forEach(line => {
      line.draw();
    });
  }
}

3. 创建线条

在main.js文件中,添加以下代码来创建线条:

class Line {
  constructor(canvas, ctx) {
    this.canvas = canvas;
    this.ctx = ctx;

    this.x = Math.random() * canvas.width; // 线条的起始x坐标
    this.y = Math.random() * canvas.height; // 线条的起始y坐标
    this.vx = Math.random() * 2 - 1; // 线条的x方向速度
    this.vy = Math.random() * 2 - 1; // 线条的y方向速度
    this.color = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`; // 线条的颜色
  }

  draw() {
    // 移动线条
    this.x += this.vx;
    this.y += this.vy;

    // 如果线条超出画布边界,则将其反弹回来
    if (this.x < 0 || this.x > this.canvas.width) {
      this.vx = -this.vx;
    }
    if (this.y < 0 || this.y > this.canvas.height) {
      this.vy = -this.vy;
    }

    // 绘制线条
    this.ctx.beginPath();
    this.ctx.strokeStyle = this.color;
    this.ctx.moveTo(this.x, this.y);
    this.ctx.lineTo(this.x + this.vx, this.y + this.vy);
    this.ctx.stroke();
  }
}

结语

现在,你已经学会了如何使用Canvas和TypeScript创建一个线条动画。你可以根据自己的需求修改代码,来创建出各种各样的线条动画。