用JavaScript做一个炫彩小球的动画,鼠标移动产生小球,片刻透明度降低到0时,小球消失。
效果如下图所示:
需要学JavaScript的dom和面向对象基础知识。
步骤:
1.构建小球类,它有半径、坐标x、y,透明度、颜色属性;有init()方法用来初始化,update()方法更新小球状态。
2.在init方法中,需要创建小球的dom节点,初始化小球的位置。
3.接着用定时器,每20ms更新一次小球的位置。
4.update()方法需要描述小球的位置变化、透明度变化、大小变化。
5.准备一个ballArr小球数组,用来放置所有的小球。
6.对document根节点进行鼠标位置移动监听,鼠标每动一次就实例化一次小球对象,并且在类中要将对象push到小球数组中。
7.在update方法中,当小球对象的透明到小于0时,通过遍历小球数组找到该小球对象并将它从数组中删除,且从节点树中删除。
<!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>小球</title>
<style>
* {
padding: 0;
margin: 0;
}
body {
background-color: #000;
}
.ball {
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<script>
// 构造小球这个类
function Ball(x, y) {
// x、y代表小球的中心点坐标
this.x = x;
this.y = y;
this.r = 5;// 小球半径
this.color = colorArr[parseInt(Math.random()*colorArr.length)];
this.opacity = 1;
// 小球位置的变化量
do {
this.dX = parseInt(Math.random() * 8 - 4);//使得位置可正可负
this.dY = parseInt(Math.random() * 8 - 4);//使得位置可正可负
}while(this.dX==0&&this.dY==0); //防止dx和dy同时为0
this.init();
// 将新建的小球对象推入数组中
ballArr.push(this);
}
Ball.prototype.init = function () {
// 创建小球节点
this.dom = document.createElement('div');
this.dom.className = "ball";
this.dom.style.backgroundColor = this.color;
this.dom.style.width = 2 * this.r + "px";
this.dom.style.height = 2 * this.r + "px";
this.dom.style.left = this.x - this.r + "px";
this.dom.style.top = this.y - this.r + "px";
document.body.appendChild(this.dom);
}
Ball.prototype.update = function () {
this.x += this.dX;
this.y += this.dY;
// 改变小球的大小
this.r += 0.2;
this.opacity -= 0.02;
this.dom.style.opacity = this.opacity;
this.dom.style.width = 2 * this.r + "px";
this.dom.style.height = 2 * this.r + "px";
this.dom.style.left = this.x - this.r + "px";
this.dom.style.top = this.y - this.r + "px";
// 当opacity为0时,从数组中删除该小球,并从节点树中移除它
if(this.opacity<=0){
// 遍历找到那个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","eeeee0","cc3399","#ff6600"];
// 用定时器更新小球的状态
setInterval(function () {
// 遍历更新小球数组
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].update();
}
}, 20);
// 鼠标滑过创建小球对象 注意直接就是document.onmousemove
document.onmousemove = function (e) {
// client 是相对于浏览器的鼠标位置
var x = e.clientX;
var y = e.clientY;
new Ball(x, y);
}
</script>
</body>
</html>