先看效果
- Js
/*小球*/
function Ball(options) {
this._init(options);
}
Ball.prototype = {
_init: function (options) {
options = options || {};
//小球属性
this.pid = options.pid; //父节点id
this.x = options.x || 0; //x坐标
this.y = options.y || 0; //y坐标
this.r = options.r || 60; //半径
this.bgColor = options.bgColor || 'red';
//小球坐标和半径的变化量
this.change_x = _.random(-5, 5);
this.change_y = _.random(-5, 5);
this.change_r = _.random(1, 3);
},
//创建小球
render: function () {
var rootNode = document.getElementById(this.pid)
var childNode = document.createElement('div');
rootNode.appendChild(childNode);
childNode.style.position = 'absolute';
childNode.style.left = this.x + 'px';
childNode.style.top = this.y + 'px';
childNode.style.width = this.r + 'px';
childNode.style.height = this.r + 'px';
childNode.style.borderRadius = '50%';
childNode.style.backgroundColor = this.bgColor;
},
//改变小球的位置
update: function () {
this.x += this.change_x;
this.y += this.change_y;
this.r -= this.change_r;
if(this.r <= 0){
this.r = 0;
return true;
}
return false;
}
}
/*一组小球*/
function Balls(options) {
this._init(options);
}
Balls.prototype = {
_init: function (options) {
this.options = options || {};
//根节点
this.rootNode = document.getElementById(this.options.pid);
//小球数量
this.totalNode = document.getElementById(this.options.total);
//颜色
this.ballColors = this.options.ballColors || ['red', 'yellow', 'blue'];
//保存小球的数组
this.balls = [];
},
render: function () {
var that = this;
that.rootNode.onmousemove = function (ev1) {
var e = ev1 || window.event;
that.options.bgColor = that.ballColors[_.random(0, that.ballColors.length-1)];
that.options.x = e.clientX;
that.options.y = e.clientY;
var ball = new Ball(that.options);
ball.render();
that.balls.push(ball);
}
//定时器
setInterval(function () {
// 清除上一帧产生的小球
for(var i=0; i<that.rootNode.children.length; i++){
that.rootNode.children[i].remove();
}
// 绘制小球和让小球移动
for(var j=0; j<that.balls.length; j++){
that.balls[j].render();
var res = that.balls[j].update();
if(res){
that.balls = _.without(that.balls, that.balls[j]);
}
}
that.totalNode.innerHTML = that.balls.length;
}, 50);
}
}
- html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>彩色小球</title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
html, body, #box{
width: 100%;
height: 100%;
}
#box{
background-color: #000;
}
#total{
background-color: #000;
color: #fff;
}
</style>
</head>
<body>
<div style="float: left;background-color: #000;color: #fff;">小球数量: </div>
<div id="total"></div>
<div id="box"></div>
//Underscore-min.js用来生成随机数等的一个工具模块
<script src="js/Underscore-min.js"></script>
<script src="js/Balls.js"></script>
<script>
var balls = new Balls({
pid: 'box',
total: 'total'
});
balls.render();
</script>
</body>
</html>