一 、红绿灯
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021062916580258.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyMTEzNzc4,size_16,color_FFFFFF,t_70)
<div id='box'></div>
<script>
function Light() {
this.color = 1
this.init();
this.bindEvent()
}
Light.prototype.init = function () {
this.img = document.createElement('img')
this.img.src = './images/light/1.png'
box.append(this.img)
}
Light.prototype.bindEvent = function () {
var that = this;
this.img.onclick = function () {
that.changeColor()
}
}
Light.prototype.changeColor = function () {
this.color++
if (this.color == 4) {
this.color = 1
}
this.img.src = `./images/light/${this.color}.png`
}
var box = document.getElementById('box')
var count = 20;
while (count--) {
new Light()
}
</script>
二、渲彩小球
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210629165943496.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyMTEzNzc4,size_16,color_FFFFFF,t_70)
<!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>Document</title>
<style>
body {
background: #000000;
}
.ball {
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<script>
function Ball(x, y) {
console.log(colorArr)
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.dY == 0 && this.dX == 0);
this.dX = parseInt(Math.random() * 20) - 10;
this.dY = parseInt(Math.random() * 20) - 10;
this.init()
ballArr.push(this)
}
Ball.prototype.init = function () {
this.div = document.createElement('div')
this.div.className = 'ball';
this.div.style.width = this.r * 2 + 'px';
this.div.style.height = this.r * 2 + 'px';
this.div.style.left = this.x - this.r + 'px';
this.div.style.top = this.y - this.r + 'px';
this.div.style.backgroundColor = this.color;
document.body.appendChild(this.div)
}
Ball.prototype.updata = function () {
console.log(this.dX)
this.x += this.dX;
this.y -= this.dY;
this.r += 0.2;
this.opacity -= 0.01;
this.div.style.width = this.r * 2 + 'px';
this.div.style.height = this.r * 2 + 'px';
this.div.style.left = this.x - this.r + 'px'
this.div.style.top = this.y - this.r + 'px';
this.div.style.opacity = this.opacity;
if (this.opacity < 0) {
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1)
}
}
document.body.removeChild(this.div)
}
}
var ballArr = []
var colorArr = ['#66CCCC', '#CCFF66', '#FF99CC', '#FF6666', '#CC3399', '#FF6600']
document.onmousemove = function (e) {
var x = e.clientX;
var y = e.clientY
console.log(x, y)
new Ball(x, y)
}
console.log(ballArr)
setInterval(() => {
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].updata()
}
}, 20);
</script>
</body>
</html>