<!DOCTYPE html>
<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>
</head>
<body>
<style>
.demo {
width: 5px;
height: 5px;
left: 200px;
top: 200px;
}
body {
background-color: black;
}
.ball {
position: absolute;
border-radius: 50%;
}
</style>
<script>
// 原理:实例多个小圆,把每个实例放到数组中,使用定时器不断去更新他。
// 初始化:实例对象,各个属性。
// 属性:X,Y,半径,透明度
// 方法:构造方法
function ball(x, y) {
// X
// y
// 透明度
// 半径
this.x = x;
this.y = y;
this.r = 20;
this.color = colorArr[parseInt(Math.random() * colorArr.length)];
this.opacity = 1;
// 这个小球的x增量和y的增量,使用do while语句,可以防止dX和dY都是零
do {
this.dx = parseInt(Math.random() * 20) - 10;
this.dy = parseInt(Math.random() * 20) - 10;
} while (this.dX == 0 && this.dY == 0)
this.init();
ballArr.push(this);
}
// 初始化做出这个小球
// 更新这个方法
// 把实例化放入数组中
// 填加事件
// 输出100个实例
ball.prototype.init = function() {
this.bdom = document.createElement('div');
this.bdom.className = "ball";
this.bdom.style.width = this.r * 2 + 'px';
this.bdom.style.height = this.r * 2 + 'px';
this.bdom.style.left = this.x - this.r + 'px';
this.bdom.style.top = this.y - this.r + 'px';
this.bdom.style.backgroundColor = this.color;
document.body.appendChild(this.bdom);
}
ball.prototype.update = function() {
this.x += this.dx;
this.y += this.dy;
this.r += 0.2;
this.opacity -= 0.01;
this.bdom.style.width = this.r * 2 + 'px';
this.bdom.style.height = this.r * 2 + 'px';
this.bdom.style.left = this.x - this.r + 'px';
this.bdom.style.top = this.y - this.r + 'px';
this.bdom.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);
}
}
// 还要删除自己的dom
document.body.removeChild(this.dom);
}
}
var ballArr = [];
var colorArr = ['#66CCCC', '#CCFF66', '#FF99CC', '#FF6666', '#CC3399', '#FF6600'];
// 定时器,负责更新所有的小球实例
setInterval(function() {
// 遍历数组,调用调用的update方法
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].update();
}
}, 20);
// 鼠标指针的监听
document.onmousemove = function(e) {
// 得到鼠标指针的位置
var x = e.clientX;
var y = e.clientY;
new ball(x, y);
};
//var ba = new ball(x, y);
</script>
</body>
</html>