做一个动态点连线的效果。
每个点会随机进行移动,点移动到靠近的点之后,就会连接到这个点,以此类推。
详情注释看源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0;
overflow: hidden;
background-color: white;
}
canvas {
display: block;
}
</style>
<title>动态连线</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// 获取 canvas 元素以及其 2D 渲染上下文
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let points = []; // 用于存储点的数组
// 设置 canvas 尺寸以匹配窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 在窗口大小调整时更新 canvas 尺寸
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// Point 类的定义
class Point {
constructor() {
// 使用随机位置和速度初始化点
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = (Math.random() - 0.5) * 2;
this.vy = (Math.random() - 0.5) * 2;
}
// 更新点的位置并处理在画布边缘的反弹
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > canvas.width) {
this.vx *= -1;
}
if (this.y < 0 || this.y > canvas.height) {
this.vy *= -1;
}
}
// 在 canvas 上绘制点
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 3, 0, Math.PI * 2);
ctx.fillStyle = 'black';
ctx.fill();
}
// 用线连接此点和另一个点
connectTo(otherPoint) {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(otherPoint.x, otherPoint.y);
ctx.strokeStyle = 'gray';
ctx.stroke();
}
}
// 动画函数
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const point of points) {
point.update();
point.draw();
for (const otherPoint of points) {
const distance = Math.sqrt((point.x - otherPoint.x) ** 2 + (point.y - otherPoint.y) ** 2);
if (distance < 100) {
point.connectTo(otherPoint);
}
}
}
requestAnimationFrame(animate);
}
// 生成指定数量的随机点
function generatePoints(numPoints) {
for (let i = 0; i < numPoints; i++) {
points.push(new Point());
}
}
// 生成 50 个随机点并开始动画
generatePoints(100);
animate();
</script>
</body>
</html>