效果:
代码:
<!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>
*{
margin: 0;
padding: 0;
}
body {
background-color: black;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="canvas">
你的浏览器暂不支持canvas
</canvas>
</body>
<script>
const myCanvas = document.querySelector('#canvas');
// 获取上下文
const ctx = myCanvas.getContext('2d');
// 设置画布和屏幕一样大小
myCanvas.width = document.documentElement.clientWidth;
myCanvas.height = document.documentElement.clientHeight;
// 用于存放创建出来的小球实例
const ballsArr = [];
// 小球类初始化数据
function Ball(x,y){
this.x = x;
this.y = y;
this.r = 20;
this.dx = parseInt(Math.random() * 18) - 9;
this.dy = parseInt(Math.random() * 18) - 9;
this.color = 'rgba('+parseInt(Math.random() * 256)+','+parseInt(Math.random() * 256)+','+parseInt(Math.random() * 256)+',0.8)';
// 将创建好的小球对象放入数组
ballsArr.push(this);
}
// 小球的画圆
Ball.prototype.render = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI * 2,true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
// 小球的路径更新以及半径减小
Ball.prototype.update = function(){
this.x += this.dx;
this.y += this.dy;
this.r--;
if (this.r <= 0) {
this.goDie();
}
}
// 当小球的半径小于等于0时,清除该小球
Ball.prototype.goDie = function(){
for (let index = 0; index < ballsArr.length; index++) {
if (this === ballsArr[index]) {
ballsArr.splice(index,1)
}
}
}
// 当鼠标滑动时创建对应鼠标位置的小球
myCanvas.onmousemove = function(event){
new Ball(event.clientX,event.clientY);
}
setInterval(()=>{
// 清屏
ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
for (let index = 0; index < ballsArr.length; index++) {
ballsArr[index].update();
ballsArr[index] && ballsArr[index].render();
}
},20);
</script>
</html>