代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
body {
margin: 0;
padding: 0;
background: linear-gradient(to bottom, #000000 0%, #5788fe 100%);
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas></canvas>
<script>
//获取canvas元素,并给canvas设置大小
var can = document.querySelector("canvas");
can.width = window.innerWidth;
can.height = window.innerHeight;
//canvas大小随浏览器一起变化
window.onresize = function() {
can.width = window.innerWidth;
can.height = window.innerHeight;
};
//获取2D绘图环境
var ctx = can.getContext("2d");
//返回一个min和max之间的一个随机整数
function randow(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
//返回一个min和max之间的一个随机小数
function random(min, max) {
return Math.random() * (max - min) + min;
}
//用来存放每个圆的属性
var dots = [];
//生成圆的个数
var arcNum = 100;
// 存储n个不同属性的圆
function createArc() {
for (var i = 0; i < arcNum; i++) {
//定义一个对象,将圆的属性存储起来
var arcObj = {
arcX: randow(0, window.innerWidth), //圆的X坐标
arcY: randow(0, window.innerHeight), //圆的Y坐标
arcR: 2, //圆的半径
color: `rgba(${randow(0, 255)},${randow(0, 255)},${randow(
0,
255
)},${random(0, 1)})`,
suduX: random(-0.5, 0.5), //圆X轴速度
suduY: random(-0.5, 0.5) //圆Y轴速度
};
dots.push(arcObj);
}
}
createArc();
// 画圆
function draw() {
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
for (var i = 0; i < arcNum; i++) {
//让圆动起来
dots[i].arcX += dots[i].suduX;
dots[i].arcY += dots[i].suduY;
ctx.beginPath();
ctx.fillStyle = dots[i].color;
ctx.arc(dots[i].arcX, dots[i].arcY, dots[i].arcR, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
//边界检测,将速度取反,实现碰撞
if (dots[i].arcX <= 0 || dots[i].arcX > window.innerWidth)
dots[i].suduX *= -1;
if (dots[i].arcY <= 0 || dots[i].arcY > window.innerHeight)
dots[i].suduY *= -1;
//利用勾股定理判断是否连线 a*a+b*b=c*c
// Math.sqrt() 平方根
// Math.pow(a,b) a的b次方
for (var j = i + 1; j < arcNum; j++) {
if (
Math.sqrt(
Math.pow(dots[i].arcX - dots[j].arcX, 2) +
Math.pow(dots[i].arcY - dots[j].arcY, 2)
) < 100
) {
ctx.beginPath();
ctx.strokeStyle = dots[i].color;
ctx.moveTo(dots[i].arcX, dots[i].arcY);
ctx.lineTo(dots[j].arcX, dots[j].arcY);
ctx.closePath();
ctx.stroke();
}
}
}
}
setInterval(draw, 60 / 1000);
//添加鼠标移动事件
can.onmousemove = function(e) {
var ev = event || e;
var mouseX = ev.offsetX;
var mouseY = ev.offsetY;
for (var i = 0; i < arcNum; i++) {
if (
Math.sqrt(
Math.pow(dots[i].arcX - mouseX, 2) +
Math.pow(dots[i].arcY - mouseY, 2)
) < 100
) {
ctx.beginPath();
ctx.strokeStyle = dots[i].color;
ctx.moveTo(mouseX, mouseY);
ctx.lineTo(dots[i].arcX, dots[i].arcY);
ctx.closePath();
ctx.stroke();
}
}
};
</script>
</body>
</html>
效果图: