前言: move鼠标路径会生成魔法棒划过的特效
- 定义一个生成圆的类
function Ball(opts) { // 基本参数 this.top = opts.top || 100; this.left = opts.left || 100; this.r = 30; this.bgColor = opts.bgColor || 'red'; this.id = opts.id; // 变化的参数 this.dT = createRandom(-10,10); this.dL = createRandom(-10,10); this.dr = createRandom(0,3); } Ball.prototype._init = function() { let parentId = document.getElementById(this.id); let childId = document.createElement('div'); parentId.appendChild(childId); childId.style.width = this.r + 'px'; childId.style.height = this.r + 'px'; childId.style.borderRadius = '50%'; childId.style.position = 'absolute'; childId.style.top = this.top + 'px'; childId.style.left = this.left + 'px'; childId.style.background = this.bgColor; } Ball.prototype.render = function() { this._init(); }-
onmousemove时更新小球属性的方法 Ball.prototype.update = function() { this.top += this.dT; this.left += this.dL; this.r -= this.dr; if(this.r <= 0) { this.r = 0; // 移除小球 ballArr = minusArr(ballArr,this.top); } }
3. 两个公用方法
// 生成随机数
function createRandom(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
// 去掉数组中的某一项
function minusArr(arr,index) {
return arr.filter(item => {
item.top !== index
})
}
4. 新建一个html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
html,body,div {
width: 100%;
height: 100%;
background: #000;
}
#app {
background: #000;
position: relative;
}
</style>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./ball.js"></script>
<script type="text/javascript">
function createRandom(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
let colorArr = ['red','green','pink','orange','yellow','gold','blue','white','gray'];
let ballArr = [];
let app = document.getElementById('app');
app.onmousemove = function(ev) {
// 生成小球
let ball = new Ball({
id: 'app',
top: ev.clientY,
left: ev.clientX,
bgColor: colorArr[createRandom(0,7)]
})
// 保存小球
ballArr.push(ball)
}
// 定时器刷新页面
setInterval(()=> {
// 清掉所有的小球
for(let j=0;j<app.children.length-1;j++) {
app.children[j].remove()
}
// 生成保存在数组中的小球
for(let i=0;i<ballArr.length-1;i++) {
ballArr[i].render();
ballArr[i].update();
}
},60)
</script>
</body>
</html>
5. 最后效果