<!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>
body {
margin: 0;
height: 100vh;
background-color: #000;
text-align: center;
}
html,
body {
overflow: hidden;
}
#c1 {
background-color: #000;
}
</style>
<script>
/** @type {HTMLCanvasElement} */
function rnd(n, m) {
return parseInt(Math.random() * (m - n) + n)
}
window.onload = function () {
var c = document.getElementById("c1");
var gd = c.getContext('2d');
const winH = document.documentElement.clientHeight;
const winW = document.documentElement.clientWidth;
c.width = winW;
c.height = winH;
const N = 40;//当前有多少点
const aPoint = [];//存取当前点的坐标
const oldArr = [];
// 点开始动起来
for (let i = 0; i < N; i++) {
aPoint[i] = {
x: rnd(0, winW),
y: rnd(0, winH),
speedX: rnd(-10, 10),
speedY: rnd(-10, 10)
}
}
// console.log(aPoint,6666);
function drawPoint(p) {
let pw = 10;
let ph = 10;
gd.fillStyle = '#fff';
gd.fillRect(p.x - pw / 2, p.y - ph / 2, pw, ph)
};
setInterval(() => {
gd.clearRect(0, 0, c.width, c.height)
for (let i = 0; i < aPoint.length; i++) {
let p = aPoint[i];
drawPoint(p);
}
for (let i = 0; i < aPoint.length; i++) {
let p = aPoint[i];
let pageW = winW - 10;
let pageH = winH - 10;
if (p.x <= 0) {
p.x = 0;
p.speedX *= -1;
}
if (p.x >= pageW) {
p.x = pageW;
p.speedX *= -1;
}
if (p.y <= 0) {
p.y = 0;
p.speedY *= -1;
}
if (p.y >= pageH) {
p.y = pageH;
p.speedY *= -1;
}
p.x += p.speedX;
p.y += p.speedY;
}
gd.beginPath();
gd.strokeStyle = '#fff';
gd.moveTo(aPoint[0].x, aPoint[0].y);
for (let i = 0; i < aPoint.length; i++) {
gd.lineTo(aPoint[i].x, aPoint[i].y)
}
gd.closePath();
gd.stroke();
let arr = [];
for (let i = 0; i < aPoint.length; i++) {
arr[i] = {
x: aPoint[i].x,
y: aPoint[i].y,
}
}
// console.log(arr,96666);
oldArr.push(arr);
while (oldArr.length > N) {
oldArr.shift();
}
// console.log(oldArr,6666);
// 画尾巴
gd.beginPath();
for (var i = 0; i < oldArr.length; i++) {
let opacity = .10 - 1 / oldArr.length;
gd.moveTo(oldArr[i][0].x, oldArr[i][0].y);
gd.strokeStyle = `rgba(${rnd(0, 256)},${rnd(0, 256)},${rnd(0, 256)},${opacity})`
for (let j = 0; j < oldArr[i].length; j++) {
gd.lineTo(oldArr[i][j].x, oldArr[i][j].y)
}
gd.closePath();
gd.stroke();
}
}, 25)
}
</script>
</head>
<body>
<canvas id="c1" width="800" height="600"></canvas>
</body>
</html>