<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>全屏彩带飘动背景动画</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
.link {
position: absolute;
bottom: 10px;
right: 10px;
color: white;
font-family: Arial, sans-serif;
text-decoration: none;
z-index: 100;
}
</style>
</head>
<body>
<canvas id="ribbonCanvas"></canvas>
<script>
// 初始化画布
const canvas = document.getElementById('ribbonCanvas');
const ctx = canvas.getContext('2d');
// 设置画布大小为窗口大小
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// 彩带参数
const ribbonCount = 30;
const ribbons = [];
const colors = [
'rgba(255, 0, 0, 0.7)',
'rgba(0, 255, 0, 0.7)',
'rgba(0, 0, 255, 0.7)',
'rgba(255, 255, 0, 0.7)',
'rgba(255, 0, 255, 0.7)',
'rgba(0, 255, 255, 0.7)',
'rgba(255, 165, 0, 0.7)',
'rgba(128, 0, 128, 0.7)'
];
// 彩带类
class Ribbon {
constructor() {
this.reset();
this.z = Math.random() * 0.5 + 0.5; // 深度值,用于3D效果
}
reset() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height * 2 - canvas.height;
this.vy = Math.random() * 2 + 1;
this.vx = Math.random() * 4 - 2;
this.size = Math.random() * 20 + 10;
this.color = colors[Math.floor(Math.random() * colors.length)];
this.segments = Math.floor(Math.random() * 10) + 5;
this.segmentLength = Math.random() * 20 + 10;
this.angle = Math.random() * Math.PI * 2;
this.va = Math.random() * 0.2 - 0.1;
}
update() {
this.y += this.vy * this.z;
this.x += this.vx * this.z;
this.angle += this.va;
// 如果彩带移出屏幕底部,重置到顶部
if (this.y > canvas.height + this.size * 2) {
this.reset();
this.y = -this.size;
}
// 如果彩带移出屏幕左右两侧,重置到另一侧
if (this.x > canvas.width + this.size) {
this.x = -this.size;
} else if (this.x < -this.size) {
this.x = canvas.width + this.size;
}
}
draw() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
let prevX = 0, prevY = 0;
for (let i = 0; i < this.segments; i++) {
const x = i * this.segmentLength;
const y = Math.sin(i * 0.5 + Date.now() * 0.005) * 10;
if (i > 0) {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(x, y);
ctx.lineWidth = this.size * (1 - i / this.segments);
ctx.strokeStyle = this.color;
ctx.stroke();
}
prevX = x;
prevY = y;
}
ctx.restore();
}
}
// 初始化彩带
for (let i = 0; i < ribbonCount; i++) {
ribbons.push(new Ribbon());
// 设置初始位置,使彩带均匀分布
ribbons[i].y = Math.random() * canvas.height;
}
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 更新并绘制所有彩带
ribbons.forEach(ribbon => {
ribbon.update();
ribbon.draw();
});
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
HTML5 Canvas 全屏彩带飘动背景动画特效
于 2025-05-19 16:03:03 首次发布
778

被折叠的 条评论
为什么被折叠?



