var canvas = document.getElementById('app');
var ctx = canvas.getContext('2d');
var ctxWidth = canvas.width;
var ctxHeight = canvas.height;
var boxObject = [];
function Box(bcolor,speed) {
this.bcolor = bcolor;
this.top = rrp(ctxWidth,ctxHeight)[1];
this.left = rrp(ctxWidth,ctxHeight)[0];
// this.direction =rrd();
this.direction =90;
this.speed = speed;
this.radius = 10;
}
Box.prototype.creatBox = function () {
ctx.beginPath();
ctx.fillStyle = this.bcolor;
// left,top,半径
ctx.arc(this.left,this.top,this.radius,0,2*Math.PI);
ctx.fill();
}
Box.prototype.moveTo = function () {
ctx.beginPath();
ctx.fillStyle = "#fff";
// left,top,半径
ctx.arc(this.left,this.top,this.radius +1,0,2*Math.PI);
ctx.fill();
// 判断是否 碰壁
if (this.left + this.radius > ctxWidth || this.left < this.radius ) {
this.direction = 180 - this.direction;
}
if (this.top + this.radius > ctxHeight || this.top < this.radius) {
this.direction = 180 - this.direction;
}
let top = this.speed * Math.sin(2*Math.PI/360*this.direction);
let left = this.speed * Math.cos(2*Math.PI/360*this.direction);
ctx.beginPath();
ctx.fillStyle = this.bcolor;
// left,top,半径
this.left += left;
this.top += top;
ctx.arc(this.left,this.top,this.radius,0,2*Math.PI);
ctx.fill();
}
start(1)
// 随机颜色显示
function rrc() {
var colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
var colorStr = '#';
for(let i = 0 ;i < 6 ;i++){
colorStr += colorArr[Math.floor(Math.random() * 15)];
}
return colorStr;
}
// 位置随机生成
function rrp(width,height) {
return [Math.random() * width,Math.random() * height]
}
function start(number) {
for(let i = 0 ;i
let box1 = new Box(rrc(),20);
box1.creatBox();
boxObject.push(box1);
}
console.log(boxObject)
setInterval(function () {
for (var i = 0; i < boxObject.length; i++) {
(boxObject[i]).moveTo();
}
},1)
}
function rrd() {
let agree = Math.floor(Math.random() * 360);
return agree;
}