<!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;
}
</style>
</head>
<body>
<canvas id="bubbleCanvas"></canvas>
<script>
// 画布设置
const canvas = document.getElementById('bubbleCanvas');
const ctx = canvas.getContext('2d');
// 设置画布为全屏
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// 气泡数组
const bubbles = [];
const bubbleCount = 100;
// 气泡类
class Bubble {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * canvas.width;
this.y = canvas.height + Math.random() * 100;
this.size = Math.random() * 20 + 5;
this.speed = Math.random() * 3 + 1;
this.opacity = Math.random() * 0.6 + 0.1;
this.color = `hsla(${Math.random() * 360}, 100%, 50%, ${this.opacity})`;
this.wave = Math.random() * 2;
this.waveSpeed = Math.random() * 0.02 + 0.01;
this.waveOffset = Math.random() * Math.PI * 2;
}
update() {
this.y -= this.speed;
this.x += Math.sin(this.waveOffset + this.y * this.waveSpeed) * this.wave;
if (this.y < -this.size) {
this.reset();
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
// 添加高光效果
ctx.beginPath();
ctx.arc(
this.x - this.size * 0.3,
this.y - this.size * 0.3,
this.size * 0.2,
0,
Math.PI * 2
);
ctx.fillStyle = `hsla(0, 100%, 100%, ${this.opacity * 0.8})`;
ctx.fill();
}
}
// 初始化气泡
for (let i = 0; i < bubbleCount; i++) {
bubbles.push(new Bubble());
// 让气泡初始位置分散
bubbles[i].y = Math.random() * canvas.height;
}
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let bubble of bubbles) {
bubble.update();
bubble.draw();
}
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
HTML5 Canvas 全屏彩色气泡动画特效
于 2025-05-19 15:59:36 首次发布
2017

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



