<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>炫彩小球球</title>
<style type="text/css">
#canvas {
border: 1px solid #CCCCCC;
}
</style>
</head>
<body>
<canvas id="canvas" width="" height=""></canvas>
</body>
</html>
<script type="text/javascript">
// 获取画布
let canvas = document.querySelector('#canvas');
// 定义宽高
canvas.width = window.innerWidth
canvas.height = window.innerHeight
// 定义为2d,circular为圆
let circular = canvas.getContext('2d');
//定义数组存取增加的圆
let CirArr = []
// 定义构造函数
function Cir(obj) {
for (let prop in obj) {
this[prop] = obj[prop]
}
this.dotX = Math.random() * 12 - 7
this.dotY = Math.random() * 12 - 7
this.color = "rgb(" + (parseInt(Math.random() * 200) + 9) + "," + (parseInt(Math.random() * 230) + 18) + ",150)";
// 存储圆
CirArr.push(this)
}
// 绘制圆
Cir.prototype.addCir = function() {
// 开始路径绘制
circular.beginPath()
// 画圆
circular.arc(this.x, this.y, this.r, 0, Math.PI*2)
circular.fillStyle = this.color
circular.fill()
}
Cir.prototype.ani = function() {
this.x += this.dotX
this.y += this.dotY
this.r--
if (this.r <= 0) {
// 清除r小于0的圆
for (let i = 0; i < CirArr.length-1; i++) {
if (CirArr[i] === this) {
CirArr.splice(i, 1)
}
}
}
}
// 鼠标移入事件
canvas.onmousemove = function(e) {
new Cir({
x: e.offsetX, //x坐标
y: e.offsetY, //y坐标
r: 30 //半径
})
}
// 设置定时器
setInterval(() => {
circular.clearRect(0, 0, window.innerWidth, window.innerHeight)
for (let i = 0; i < CirArr.length-1; i++) {
CirArr[i].ani()
CirArr[i].addCir()
}
},20)
</script>