console
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
background-color: #000;
}
.ball {
position: absolute;
border-radius: 50%;
}
</style>
</head>
<body>
<script>
function Ball(x, y) {
this.x = x;
this.y = y;
this.r = 20;
// 小球的背景颜色
this.color = colorArr[parseInt(Math.random() * colorArr.length)];
// 小球的透明度
this.opacity = 1;
do {
this.dX = parseInt(Math.random() * 20) - 10 //这个地方为什么是这样的,解决:-3到4之间随机
this.dY = parseInt(Math.random() * 20) - 10
} while (this.dY == 0 && this.dX == 0);
// 调用自己的初始化方法
this.init();
// 把自己推入数组,注意,这里的this不是类,而是实例
ballArr.push(this); //这个地方理解不了
}
// init方法
Ball.prototype.init = function () {
this.dom = document.createElement('div');
this.dom.className = 'ball';
this.dom.style.width = this.r * 2 + 'px';
this.dom.style.height = this.r * 2 + 'px';
this.dom.style.left = this.x - this.r + 'px';
this.dom.style.top = this.y - this.r + 'px';
this.dom.style.backgroundColor = this.color;
// 上树
document.body.appendChild(this.dom);
}
// 更新方法
Ball.prototype.updata = function () {
this.x += this.dX;
this.y += this.dY;
this.r += 0.2;
this.opacity -= 0.005;
this.dom.style.width = this.r * 2 + 'px';
this.dom.style.height = this.r * 2 + 'px';
this.dom.style.left = this.x - this.r + 'px';
this.dom.style.top = this.y - this.r + 'px';
this.dom.style.backgroundColor = this.color;
this.dom.style.opacity = this.opacity;
// 当透明度小于0的时候就要从数组中删除自己,dom元素也要删除自己
if (this.opacity <= 0) {
// 从数组中删除自己
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1);
}
}
document.body.removeChild(this.dom);
}
};
// 把所有小球的实例写进一个数组中去
var ballArr = [];
// 颜色数组
var colorArr = ['#66CCCC', '#CCFF66', '#FF99CC', '#FF6666',
'#CC3399', '#FF6600'
];
// 定时器负责更新小球实例
setInterval(function () {
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].updata();
}
}, 1); //我先开始做的时候显得卡顿的地方
document.onmousemove = function (e) {
//得到鼠标的位置
var x = e.clientX;
var y = e.clientY;
new Ball(x, y);
};
</script>
</body>
</html>