</>
F11

Canvas 气泡漂浮动画效果实现思路:

1.获取鼠标移动 x,y 坐标

  1. //鼠标移动
  2. canvas.onmousemove = function(e) {
  3.     mouseX = e.clientX;
  4.     mouseY = e.clientY;
  5. }

2.将一定数量的气泡x,y坐标与随机 radius 半径 push() 到 Circle 对象中

  1. //气泡数量函数
  2. function count(){
  3.     //循环气泡数量,将随机数据 push 到 circleArray 数组中
  4.     for (var i = 0; i < 800; i++) {
  5.         var randomXCoordinate = Math.random() * canvasWidth;
  6.         var randomYCoordinate = Math.random() * canvasHeight;
  7.         var randomRadius = Math.random() * 5;
  8.         circleArray.push(new Circle(randomXCoordinate,randomYCoordinate ,randomRadius))
  9.     }
  10. }

3.循环更新 Circle 函数,绘制气泡,随机增减气泡x,y坐标,实现气泡移动效果。当鼠标指针与气泡距离接近0时,增加气泡半径。

  1. //距离接近0时,增加半径
  2. this.update = function() {
  3.     this.xCoordinate += this.xVelocity;         //气泡x坐标,随着随机数的 True Or False 的判断,在改变
  4.     this.yCoordinate += this.yVelocity;         //气泡y坐标,随着随机数的 True Or False 的判断,在改变
  5.     var xDistance = mouseX - this.xCoordinate;  //x距离(鼠标x坐标 -  气泡x坐标 = 距离)
  6.     var yDistance = mouseY - this.yCoordinate;  //y距离(鼠标y坐标 -  气泡y坐标 = 距离)
  7.     var originalRadius = radius;
  8.  
  9.  
  10.     //移动函数
  11.     if (this.xCoordinate + this.radius > canvasWidth || this.xCoordinate - this.radius < 0) {
  12.         this.xVelocity = -this.xVelocity;
  13.     };  
  14.     if (this.yCoordinate + this.radius > canvasHeight || this.yCoordinate - this.radius < 0) {
  15.         this.yVelocity = - this.yVelocity;  
  16.     };
  17.  
  18.     //半径增减函数,气泡最大半径 maxRadius  = 35
  19.     if (xDistance < 50 && xDistance > -50 && this.radius < maxRadius && yDistance < 50 && yDistance > -50) {
  20.         this.radius += 2;
  21.     } else if ((xDistance >= 50 && originalRadius < this.radius) || (xDistance <= -50 && originalRadius < this.radius) || (yDistance >= 50 && originalRadius < this.radius) || (yDistance <= -50 && originalRadius < this.radius)) {
  22.         if (this.radius > 3) {
  23.             this.radius -= 2;
  24.         }
  25.     };
  26.  
  27.     this.draw();
  28. }
  29.  
  30. //绘制气泡
  31. this.draw = function() {
  32.     c.beginPath();
  33.     c.arc(this.xCoordinate, this.yCoordinate, this.radius, 0, Math.PI * 2)
  34.     c.fillStyle = this.color;
  35.     c.fill();
  36. }