js实现气泡效果
使用CSS和JavaScript创建气泡效果
气泡效果可以通过CSS动画和JavaScript动态生成元素来实现。以下是一个简单的实现方法:
CSS样式部分
.bubble {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.6);
pointer-events: none;
animation: float 4s ease-in-out infinite;
}
@keyframes float {
0% {
transform: translateY(0) rotate(0deg);
opacity: 1;
}
100% {
transform: translateY(-100px) rotate(360deg);
opacity: 0;
}
}
JavaScript实现部分
function createBubble(event) {
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 = `${event.clientX - size/2}px`;
bubble.style.top = `${event.clientY - size/2}px`;
document.body.appendChild(bubble);
setTimeout(() => {
bubble.remove();
}, 4000);
}
document.addEventListener('mousemove', createBubble);
使用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(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 20 + 5;
this.speed = Math.random() * 2 + 1;
this.opacity = Math.random() * 0.5 + 0.3;
this.angle = Math.random() * Math.PI * 2;
}
update() {
this.y -= this.speed;
this.x += Math.sin(this.angle) * 0.5;
this.angle += 0.01;
this.opacity -= 0.005;
}
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();
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
bubbles.forEach((bubble, index) => {
bubble.update();
bubble.draw();
if(bubble.opacity <= 0) {
bubbles.splice(index, 1);
}
});
requestAnimationFrame(animate);
}
document.addEventListener('mousemove', (e) => {
bubbles.push(new Bubble(e.clientX, e.clientY));
});
animate();
气泡效果的优化建议
调整气泡大小、速度和透明度范围可以创建不同的视觉效果。增加随机颜色可以增强视觉吸引力:

// 在Bubble类中添加颜色属性
this.color = `hsl(${Math.random() * 360}, 100%, 80%)`;
// 修改draw方法
ctx.fillStyle = `hsla(${this.color}, ${this.opacity})`;
对于性能优化,可以限制同时存在的气泡数量,或者在移动端减少气泡生成频率。






