原生JavaScript实现五色小球
一,HTML代码
<div id="ball">div>
<script src="underscore.js">script>
二,CSS代码
*{
margin: 0;
padding: 0;
border: 0;
}
body{
width: 100%;
height:100%;
background-color: #000000;
}
#ball{
width: 100%;
height:100%;
background-color: #000000;
}
三,JavaScript代码
function Ball(options) {
this._init(options) ;
}
Ball.prototype = {
_init: function(options) {
var option = options || {
};
this.width = option.width || 30;
this.height = option.height || 30;
this.left = option.left;
this.top = option.top;
this.borderRadius = option.borderRadius || '50%';
this.backgroundColor = option.backgroundColor || '#0094ff';
},
getCssAttr:function(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
} else {
return window.getComputedStyle(obj,null).getPropertyValue(attr);
}
},
create: function() {
var _ball = document.createElement('div');
_ball.style.position = 'absolute';
_ball.style.left = this.left + 'px';
_ball.style.top = this.top + 'px';
_ball.style.width = this.width + 'px';
_ball.style.height = this.height + 'px';
_ball.style.borderRadius = this.borderRadius;
_ball.style.backgroundColor = this.backgroundColor;
return _ball;
},
render: function() {
var b = this.create();
document.body.appendChild(b);
this.removeBall(b);
},
removeBall: function(ballObj) {
var timer = null;
clearTimeout(timer);
timer = setTimeout(function() {
var rl = Math.random();
var rt = Math.random();
this.animate(ballObj, {
width: 0,
height: 0,
left: this.left + parseInt(Math.random() * (rl < 0.5 ? 200 : -200)),
top: this.top + parseInt(Math.random() * (rt > 0.5 ? 200 : -200))
}, function() {
document.body.removeChild(ballObj);
})
}.bind(this), 100)
},
animate: function(obj, dic, fn) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var flag = true;
for (var key in dic) {
var begin = parseInt(this.getCssAttr(obj, key));
var target = parseInt(dic[key]);
var speed = (target - begin) * 0.2;
speed = target > begin ? Math.ceil(speed) : Math.floor(speed);
obj.style[key] = begin + speed + 'px';
if (target != begin) {
flag = false;
}
}
if (flag) {
if (fn) {
fn();
}
clearInterval(obj.timer);
}
}.bind(this), 60)
}
};
document.onmousedown = function(){
return false;
};
document.onmousemove = function(event) {
if (document.body.children.length > 200) {
return false;
}
var event = event || window.event;
var x = event.clientX + _.random(-5, 5);
var y = event.clientY + _.random(-5, 5);
var r = parseInt(Math.random() * 256);
var g = parseInt(Math.random() * 256);
var b = parseInt(Math.random() * 256);
var bgc = 'rgb(' + r + ',' + g + ',' + b + ')';
var ball = new Ball({
width: 50,
height: 50,
top: y - 25,
left: x - 25,
borderRadius: '50%',
backgroundColor: bgc
});
ball.render();
}
四,实现效果