<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5动态线条像素背景动画特效</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, sans-serif;
}
canvas {
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
.content {
color: white;
text-align: center;
padding: 20px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 10px;
max-width: 600px;
}
h1 {
margin-bottom: 20px;
}
a {
color: #4CAF50;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div class="content">
<h1>HTML5动态线条像素背景动画特效</h1>
<p>这是一个使用HTML5 Canvas创建的动态线条像素背景动画。</p>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置canvas大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 线条数组
const lines = [];
const lineCount = 100;
const maxDistance = 150;
// 线条类
class Line {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 - 1;
this.radius = Math.random() * 1.5 + 0.5;
this.color = `rgba(${Math.floor(Math.random() * 56 + 200)}, ${Math.floor(Math.random() * 56 + 200)}, ${Math.floor(Math.random() * 56 + 200)}, ${Math.random() * 0.4 + 0.1})`;
}
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;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
// 初始化线条
for (let i = 0; i < lineCount; i++) {
lines.push(new Line());
}
// 绘制连接线
function drawConnections() {
for (let i = 0; i < lines.length; i++) {
for (let j = i + 1; j < lines.length; j++) {
const dx = lines[i].x - lines[j].x;
const dy = lines[i].y - lines[j].y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < maxDistance) {
const opacity = 1 - distance / maxDistance;
ctx.strokeStyle = `rgba(200, 200, 200, ${opacity * 0.2})`;
ctx.lineWidth = opacity * 1.5;
ctx.beginPath();
ctx.moveTo(lines[i].x, lines[i].y);
ctx.lineTo(lines[j].x, lines[j].y);
ctx.stroke();
}
}
}
}
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 更新和绘制所有线条
lines.forEach(line => {
line.update();
line.draw();
});
// 绘制连接线
drawConnections();
requestAnimationFrame(animate);
}
// 开始动画
animate();
// 窗口大小改变时重置canvas大小
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>