js实现气泡效果
使用CSS和JavaScript创建气泡效果
通过CSS动画结合JavaScript动态生成元素,可以实现气泡上升的视觉效果。以下是实现方法:
HTML基础结构

<div id="bubble-container"></div>
CSS样式设置
.bubble {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.6);
pointer-events: none;
animation: float 4s ease-in infinite;
}
@keyframes float {
0% {
transform: translateY(0) rotate(0deg);
opacity: 1;
}
100% {
transform: translateY(-100vh) rotate(360deg);
opacity: 0;
}
}
JavaScript实现逻辑

function createBubble() {
const container = document.getElementById('bubble-container');
const bubble = document.createElement('div');
bubble.className = 'bubble';
// 随机大小
const size = Math.random() * 30 + 10;
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
// 随机位置
bubble.style.left = `${Math.random() * 100}%`;
// 随机动画时长
const duration = Math.random() * 3 + 2;
bubble.style.animationDuration = `${duration}s`;
container.appendChild(bubble);
// 动画结束后移除元素
bubble.addEventListener('animationend', () => {
bubble.remove();
});
}
// 定期生成气泡
setInterval(createBubble, 300);
鼠标交互气泡效果
实现跟随鼠标移动或点击产生气泡的交互效果:
document.addEventListener('mousemove', (e) => {
const bubble = document.createElement('div');
bubble.className = 'bubble';
// 设置位置为鼠标位置
bubble.style.left = `${e.clientX}px`;
bubble.style.top = `${e.clientY}px`;
// 随机大小和动画
const size = Math.random() * 20 + 5;
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
bubble.style.animationDuration = `${Math.random() * 2 + 1}s`;
document.body.appendChild(bubble);
// 动画结束后移除
bubble.addEventListener('animationend', () => {
bubble.remove();
});
});
Canvas高性能气泡实现
对于需要大量气泡的场景,使用Canvas性能更佳:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
canvas.style.position = 'fixed';
canvas.style.top = '0';
canvas.style.left = '0';
canvas.style.pointerEvents = 'none';
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
const bubbles = [];
class Bubble {
constructor() {
this.x = Math.random() * canvas.width;
this.y = canvas.height + Math.random() * 50;
this.size = Math.random() * 20 + 5;
this.speed = Math.random() * 2 + 1;
this.opacity = Math.random() * 0.5 + 0.3;
}
update() {
this.y -= this.speed;
if (this.y < -this.size) {
this.y = canvas.height + Math.random() * 50;
this.x = Math.random() * canvas.width;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${this.opacity})`;
ctx.fill();
}
}
// 初始化气泡
for (let i = 0; i < 50; i++) {
bubbles.push(new Bubble());
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
bubbles.forEach(bubble => {
bubble.update();
bubble.draw();
});
requestAnimationFrame(animate);
}
animate();
这些方法可以根据具体需求调整参数,如气泡大小、速度、透明度等,以获得理想的视觉效果。Canvas实现适合大量粒子场景,而CSS动画方案更适合简单的UI增强效果。






