改动了一下逻辑,球多的时候比较卡
这样子,当小球比较多的时候,特别卡,是怎么回事,求老师帮忙分析一下
在这里输入代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body{
background-color: #222;
overflow: hidden;
}
.ball{
/* background-color: red; */
position: absolute;
border-radius: 50%;
}
</style>
<body>
<script>
// 鼠标滑动产生小球
function Ball(x, y){
// x, y 是小球的圆心
this.x = x;
this.y = y;
// 小球的半径
this.r = 20;
// 小球的颜色
this.color = colorArr[parseInt(Math.random() * colorArr.length)];
// 小球的透明度
this.opacity = 1
// 小球移动的速度
do {
this.dX = parseInt(Math.random() * 20) - 10;
this.dY = parseInt(Math.random() * 20) - 10;
} while (this.dX == 0 && this.dY == 0)
this.init()
this.update()
// BallArr.push(this)
}
Ball.prototype.init = function(){
// console.log(1)
this.dom = document.createElement('div')
this.dom.className = 'ball'
this.dom.style.backgroundColor = this.color
// this.dom.style.opacity = 1
this.dom.style.width = this.r * 2 + 'px'
this.dom.style.height = this.r * 2 + '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(){
var self = this
this.timer = setInterval(function(){
console.log(1)
self.x -= self.dX;
self.y -= self.dY;
self.opacity -= 0.01
self.dom.style.opacity = self.opacity;
self.dom.style.left = self.x - self.r + 'px'
self.dom.style.top = self.y - self.r + 'px'
document.body.appendChild(self.dom)
if (self.dom.style.opacity < 0) {
document.body.removeChild(self.dom)
clearInterval(self.timer)
}
}, 20)
}
// var BallArr = []
// 初始颜色数组
var colorArr = ['#66CCCC', '#CCFF66', '#FF99CC', '#FF6666',
'#CC3399', '#FF6600'];
// 鼠标指针的监听
document.onmousemove = function (e) {
// 得到鼠标指针的位置
var x = e.clientX;
var y = e.clientY;
new Ball(x, y);
};
</script>
</body>
</html>
,可通过选择【代码语言】突出显示
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星