<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>五彩特效</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
html,
body,
div {
width: 100%;
height: 100%;
}
#box {
position: relative;
background: #000;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script src="js/ball.js"></script>
<!-- <script>
var ball = new Ball({
parentId: 'box',
left: 100,
top: 200,
bgColor: 'yellow'
})
ball.render()
</script> -->
<script>
// min and max included
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// 1. 获取当前盒子的node
var box = document.getElementById('box');
// 数组的颜色
var colorArr = ['red', 'white', 'green', 'pink', 'blue', 'red', 'yellow', 'purple'];
// 存放创建小球
var ballArr = [];
// 2. 监听鼠标在盒子上的移动
box.onmousemove = function(ev) {
// console.info(ev)
// 创建小球
var ball = new Ball({
parentId: 'box',
left: ev.clientX, // 当前鼠标X坐标
top: ev.clientY, // 当前鼠标Y坐标
bgColor: colorArr[randomIntFromInterval(0, colorArr.length - 1)] // 颜色随机
});
ballArr.push(ball) // 将每次创建出来的小球存起一个数组
};
// 3. 设置定时器
setInterval(() => {
// 3.1 清除上一针的小球
for (var i = 0; i < box.children.length; i++) {
box.children[i].remove()
}
// 3.2 让小球移动 变小
for (var j = 0; j < ballArr.length; j++) {
ballArr[j].render()
ballArr[j].update()
}
}, 50);
</script>
</html>
function Ball(options) {
this._init(options)
}
Ball.prototype = {
// 初始化
_init: function(options) {
// 圆的必要属性
this.parentId = options.parentId;
this.left = options.left;
this.top = options.top;
this.r = 60;
this.bgColor = options.bgColor || 'red'
// 小球的变化量
this.dX = randomIntFromInterval(-5, 5); // 水平
this.dY = randomIntFromInterval(-5, 5); // 垂直
this.dR = randomIntFromInterval(1, 3); // 圆的半径
},
// 渲染
render: function() {
var parentNode = document.getElementById(this.parentId);
var childNode = document.createElement('div');
parentNode.appendChild(childNode)
childNode.style.position = 'absolute';
childNode.style.left = this.left + 'px';
childNode.style.top = this.top + '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.left += this.dX;
this.top += this.dY;
this.r -= this.dR;
// 圆的半径小0的时候 干掉小球
if (this.r <= 0) {
this.r = 0;
// 过滤r=0的小球
ballArr = ballArr.filter(item => item.r != 0);
}
}
};