基于canvas的鼠标跟随粒子动画

这是最近小编在做博客时想到的网页特效

1.鼠标动画主类
class MouseMoveAnimation {
  constructor() {
    // 用于存储圆球的数组
    this.circlePool = [];
    this.init();
  }
  //   初始化
  init() {
    this.canvas = document.createElement("canvas");
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.context = this.canvas.getContext("2d");
    this.canvas.style.cssText = `
        position: fixed;
        left:0;
        top:0;
        z-index:9999;
        pointer-events: none;
    `;
    document.body.appendChild(this.canvas);
    document.addEventListener("mousemove", (e) => {
      const circle = new Circle({
        x: e.clientX, //圆心x轴坐标
        y: e.clientY, //圆心y轴坐标
        r: Math.random() * 50, //圆球半径
      });
      this.circlePool.push(circle);
    });
  }
  //   更新特效
  update() {
    this.context.clearRect(0, 0, window.innerWidth, window.innerHeight);
    this.circlePool.forEach((circle, index) => {
      circle.render(this.context);
      circle.update();
      if (circle.r <= 0) {
        this.circlePool.splice(index, 1);
      }
    });
  }
  //   特效开始
  start() {
    setInterval(() => {
      this.update();
    }, 20);
  }
}
2.圆球类
class Circle {
  constructor({ x, y, r }) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.color = `rgba(${this.randomColor()},${this.randomColor()},${this.randomColor()},${Math.random()})`;
    this.moveY = this.moveX = Math.random() * 10 - 5;
  }
  //   渲染圆球
  render(context) {
    context.beginPath();
    context.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    context.fillStyle = this.color;
    context.closePath();
    context.fill();
  }
  //   更新圆球状态
  update() {
    this.x += this.moveX;
    this.y += this.moveY;
    this.r--;
  }
  //   返回随机颜色
  randomColor() {
    return Math.round(Math.random() * 255);
  }
}
3.如何运用
new MouseMoveAnimation().start();// 运行这行代码,特效即可生效

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值