话不多说,上代码和效果图
<!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>
canvas {
border: 1px solid #444;
margin: 0 auto;
display: block;
}
</style>
</head>
<body>
<canvas id="canvas" width="500px" height="500px"
>浏览器版本过低,请升级最新版本谷歌浏览器(只有低版本浏览器才会显示标签内的文字)</canvas
>
</body>
<script>
//获取canvas画布
var canvas = document.querySelector('#canvas');
// //获取上下文
var ctx = canvas.getContext('2d');
var w = 500;
var h = 500;
var titleArr = ['A', 'B', 'C', 'D', 'E', 'F'];
//创建小球
//第一步:创建小球类
var text = '12';
function Ball(text) {
this.x = random_num(400) + 50;
this.y = random_num(400) + 50;
this.r = random_num(20) + 10;
//两种生成随机颜色的方法
this.color = random_color();
// this.color = '#' + parseInt(Math.random() * 0xffffff).toString(16);
this.speedX = random_num(3) + 2;
this.speedY = random_num(3) + 1;
this.text = text;
}
//第二步:定义小球显示方法
Ball.prototype.show = function () {
this.run();
drawCircle(this.x, this.y, this.r, this.color);
drawText(this.text, this.x + this.r, this.y);
};
//第三步:定义小球触壁改向的方法
Ball.prototype.run = function () {
if (this.x - this.r <= 0 || this.x + this.r >= w) {
this.speedX = -this.speedX;
}
if (this.y - this.r <= 0 || this.y + this.r >= h) {
this.speedY = -this.speedY;
}
this.x = this.x + this.speedX;
this.y = this.y + this.speedY;
};
//第四步:创建小球数量并加入小球数组
var ballArr = [];
for (var i = 0; i < 6; i++) {
var ball = new Ball(titleArr[i]);
ballArr.push(ball);
ball.show();
//小球连线(让当前小球和前面的小球连线)
for (var j = 0; j < i; j++) {
var prevBall = ballArr[j];
drawLine(ball.x, ball.y, prevBall.x, prevBall.y, ball.color);
}
}
//第五步:让创建好的小球运动
setInterval(() => {
ctx.clearRect(0, 0, w, h); //先清除画布
for (var i = 0; i < ballArr.length; i++) {
var ball = ballArr[i];
//小球连线(让当前小球和前面的小球连线)
for (var j = 0; j < i; j++) {
var prevBall = ballArr[j];
drawLine(ball.x, ball.y, prevBall.x, prevBall.y, ball.color);
}
//再次调用小球显示方法
ball.show();
}
}, 20);
//封装画直线
function drawLine(x1, y1, x2, y2, color, width) {
//开启一条路径
ctx.beginPath();
// //确定起始点
ctx.moveTo(x1, y1);
// //到哪里结束
ctx.lineTo(x2, y2);
// //关闭路径
ctx.closePath();
//设置颜色
ctx.strokeStyle = color;
//设置线宽
ctx.lineWidth = width;
//着色(如果要设置颜色和线宽,务必在着色之前设置)
ctx.stroke();
}
//封装画实心圆
function drawCircle(x, y, r, color, text) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.fillStyle = color;
ctx.fill();
}
//封装画文字
function drawText(text, x, y) {
ctx.font = '20px 宋体 bold';
ctx.textBaseline = 'middle';
ctx.fillText(text, x, y);
}
//封装产生随机数
function random_num(num) {
return parseInt(Math.random() * num);
}
//生成rgb随机颜色
function random_color() {
var rgb =
'rgb(' +
Math.floor(Math.random() * 255) +
',' +
Math.floor(Math.random() * 255) +
',' +
Math.floor(Math.random() * 255) +
')';
console.log(rgb);
return rgb;
}
</script>
</html>