思路:获取鼠标的位置,画球;每画一个调整位置和大小这些…
<!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>
div {
display: grid;
place-items: center;
width: 100%;
height: 100vh;
}
canvas {
border: 1px solid skyblue;
}
</style>
</head>
<body>
<div>
<canvas width="600" height="600" id="myCanvas"></canvas>
</div>
<script>
let myCanvas = document.getElementById("myCanvas");
let ctx = myCanvas.getContext("2d");
//球类
function Ball(x, y, r, color, dx, dy) {
this.x = x;
this.y = y;
this.r = r;
this.color = getRandom();
this.dx = parseInt(Math.random() * 10) - 5;
this.dy = parseInt(Math.random() * 10) - 5;
ballArr.push(this)
}
// // 渲染小球
// Ball.prototype.render = function() {
// console.log(this.color, this.x, this.y, this.r)
// ctx.beginPath();
// ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
// ctx.fillStyle = this.color;
// ctx.fill()
// };
// Ball.prototype.update = function() {
// //小球的运动
// this.x += this.dx;
// this.y += this.dy;
// this.r -= 0.4;
// if (this.r < 0) {
// this.remove()
// }
// }
// Ball.prototype.remove = function() {
// for (let i = 0; i < ballArr.length; i++) {
// if (ballArr[i] == this) {
// ballArr.splice(i, 1)
// }
// }
// }
Ball.prototype = {
constructor: Ball,
// 渲染小球
render() {
console.log(this.color, this.x, this.y, this.r)
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill()
},
//小球的运动
update() {
this.x += this.dx;
this.y += this.dy;
this.r -= 0.4;
if (this.r < 0) {
this.remove()
}
},
// 移除
remove() {
for (let i = 0; i < ballArr.length; i++) {
if (ballArr[i] == this) {
ballArr.splice(i, 1)
}
}
}
}
// 设置鼠标监听
myCanvas.addEventListener('mousemove', function(event) {
// console.log(event)
new Ball(event.offsetX, event.offsetY, 50)
})
// 维护小球的数组
let ballArr = []
// 定时器进行更新h和动画渲染
setInterval(function() {
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height)
// console.log(ballArr)
for (let i = 0; i < ballArr.length; i++) {
ballArr[i].render()
ballArr[i].update()
}
}, 50)
// 随机颜色
function getRandom() {
let allType = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
let allTypeArr = allType.split(",");
let color = "#";
for (let i = 0; i < 6; i++) {
let random = parseInt(Math.random() * allTypeArr.length);
color += allTypeArr[random]
}
return color;
}
</script>
</body>
</html>