【个人提升】canvas气泡漂浮动画

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

1.获取鼠标移动的x、y坐标

//鼠标滑动

canvas.onmousemove = function(e){

mouseX = e.clientX;

mouseY = e.clientY;

}

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

//气泡数量函数

function count()

//循环气泡数量,将随机数据 push 到 circleArray 数组中

for (var i = 0; i < 800; i++) {

 var randomXCoordinate = Math.random() * canvasWidth;

 var randomYCoordinate = Math.random() * canvasHeight;

 var randomRadius = Math.random() * 5;

circleArray.push(new Circle(randomXCoordinate,randomYCoordinate ,randomRadius))

  }

}

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

//距离接近0时,增加半径

this.update = function() {

 this.xCoordinate += this.xVelocity; //气泡x坐标,随着随机数的 True Or False 的判断,在改变

 this.yCoordinate += this.yVelocity; //气泡y坐标,随着随机数的 True Or False 的判断,在改变

var xDistance = mouseX - this.xCoordinate; //x距离(鼠标x坐标 - 气泡x坐标 = 距离)

 var yDistance = mouseY - this.yCoordinate; //y距离(鼠标y坐标 - 气泡y坐标 = 距离)

  var originalRadius = radius;

//移动函数

if (this.xCoordinate + this.radius > canvasWidth || this.xCoordinate - this.radius < 0) {

  this.xVelocity = -this.xVelocity;

 };

 if (this.yCoordinate + this.radius > canvasHeight || this.yCoordinate - this.radius < 0) {

 this.yVelocity = - this.yVelocity;

};

 //半径增减函数,气泡最大半径 maxRadius = 35

 if (xDistance < 50 && xDistance > -50 && this.radius < maxRadius && yDistance < 50 && yDistance > -50) {

 this.radius += 2;

} else if ((xDistance >= 50 && originalRadius < this.radius) || (xDistance <= -50 && originalRadius < this.radius) || (yDistance >= 50 && originalRadius < this.radius) || (yDistance <= -50 && originalRadius < this.radius)) {

 if (this.radius > 3) {

 this.radius -= 2;

}

};

 this.draw();

}

//绘制气泡

 this.draw = function() {

 c.beginPath();

  c.arc(this.xCoordinate, this.yCoordinate, this.radius, 0, Math.PI * 2)

 c.fillStyle = this.color;

 c.fill();

}

你可能感兴趣的:(【个人提升】canvas气泡漂浮动画)