js面向对象——炫彩小灯
在这里插入代码片
<!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>js面向对象实例----炫彩小球</title>
<style>
body {
background-color: black;
}
.ball {
position: absolute;
border-radius: 50%;
}
</style>
</head>
<body>
<!-- 鼠标移动,产生小球,小球位置\半径\颜色\透明度会发生变化 -->
<script>
// 定义球类
function Ball(x, y) {
// 小球的初始位置,这里的x,y指的是圆心
this.x = x
this.y = y
// 每次更新,x y的增量 设置do while域居防止da dy都是0
do {
this.dx = parseInt(Math.random() * 10) - 4
this.dy = parseInt(Math.random() * 10) - 4
} while (this.dx == 0 && this.dy == 0)
// 小球半径
this.r = 10
// 小球透明度
this.opacity = 1
// 小球颜色,从数组中随机选择一个颜色
this.color = colorArr[parseInt(Math.random() * colorArr.length)]
// 调用自己的init() 不初始化就不能产生元素)
this.init()
// 将自己---小球实例都推入数组中
ballArr.push(this)
}
// 初始化方法
Ball.prototype.init = function () {
// 创建对象的dom节点
this.dom = document.createElement('div')
// 设置节点的属性
// 类名,方便设置css
this.dom.className = 'ball'
//宽高
this.dom.style.width = this.r * 2 + 'px'
this.dom.style.height = this.r * 2 + 'px'
// 位置
this.dom.style.top = this.y - this.r + 'px'
this.dom.style.left = this.x - this.r + 'px'
// 透明度
this.dom.style.opacity = this.opacity
// 颜色
this.dom.style.backgroundColor = this.color
// 上树
document.body.appendChild(this.dom)
}
// 更新
Ball.prototype.update = function () {
// 更新位置
this.x += this.dx
this.y += this.dy
// 更新半径
this.r += 0.4
// 更新透明度
this.opacity -= 0.02
// 改变dom上的属性值
this.dom.style.width = this.r * 2 + 'px'
this.dom.style.height = this.r * 2 + 'px'
this.dom.style.top = this.y - this.r + 'px'
this.dom.style.left = this.x - this.r + 'px'
this.dom.style.opacity = this.opacity
// 当透明度小于0时,要从数组中删除自己及dom元素
if (this.opacity < 0) {
// 从数组中删除自己
for (var i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1)
}
}
// 还要删除自己的dom
document.body.removeChild(this.dom)
}
}
var colorArr = ['#fa8e8e', '#a5f15d', '#69f0fa', '#cf76c0', '#f5e663', '#f3ae18']
//创建多个小球
// 将创建的实例都放到一个数组中
var ballArr = []
// 创建一个实例
// var ball = new Ball(200, 200)
// 定时器,负责更新所有的小球实例
setInterval(function () {
// 遍历数组调用update函数
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].update()
}
}, 20)
// 鼠标指针的监听
document.onmousemove = function (e) {
// 鼠标指针的位置
var x = e.clientX
var y = e.clientY
// 指针指哪就在哪创建实例
new Ball(x, y)
}
</script>
</body>
</html>