试着用面向对象的方式用canvas去实现一些东西,
主要代码
function Bubble() {}; //构造函数
Bubble.prototype = {
init: function () { //基本配置
this.x = random(0, w); //小球x轴初始位置
this.y = random(0, h); //小球y轴初始位置
this.r = random(20, 100); //小球的半径范围
this.color = 'rgba(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ',' + random(0.1, 1) +')';
this.vx = random(-1, 1);
this.vy = random(-1, 1);
this.isMove = false
},
draw: function () { //绘制小球
canCon.beginPath(); //把笔抬起来,beginPath() 方法开始一条路径,或重置当前的路径。
canCon.fillStyle = this.color;
canCon.arc(this.x, this.y, this.r, 0, Math.PI * 2); //圆心的位置,xy,半径,画圆
canCon.fill();
},
move: function () {
if(this.isMove) {
this.isMove = false
return;
}
this.x += this.vx;
this.y += this.vy;
// 检测小球与小球碰撞
var isCollision = collision(this);
if (!isCollision) {
}
//检测小球与边框碰撞
if (this.x - this.r < 0 || this.x + this.r > w) {
this.vx = -this.vx
}
if (this.y - this.r < 0 || this.y + this.r > h) {
this.vy = -this.vy
}
this.draw();
}
}
function collision (c_ball) {
var find = false
var isCollision = false
for (var ball of aBubble) {
if(ball != c_ball) {
var dxv = c_ball.x + c_ball.vx - (ball.x + ball.vx);
var dyv = c_ball.y + c_ball.vy - (ball.y + ball.vy);
var distance = Math.sqrt(dxv * dxv + dyv * dyv);
if (distance <= (c_ball.r + ball.r)) {
var dvx = c_ball.vx - ball.vx;
var dvy = c_ball.vy - ball.vy;
var dx = c_ball.x - ball.x;
var dy = c_ball.y - ball.y;
var xx_yy = dx * dx + dy * dy;
var v_dvx = (dvx * dx * dx + dvy * dx * dy) / xx_yy;
var v_dvy = (dvy * dy * dy + dvx * dx * dy) / xx_yy;
c_ball.vx = checkSpeed(c_ball.vx - v_dvx);
c_ball.vy = checkSpeed(c_ball.vy - v_dvy);
ball.vx = checkSpeed(ball.vx + v_dvx);
ball.vy = checkSpeed(ball.vy + v_dvy);
if (find) {
//避免当前循环重复移动
ball.isMove = true
//避免闪烁
ball.draw();
}
isCollision = true
}
} else {
find = true
}
}
return isCollision;
}
源码在这里
https://download.csdn.net/download/shishuwei111/11244810