js 实现弹幕
实现弹幕的基本原理
弹幕的核心是在屏幕上横向移动的文本元素,通常从右向左滑动。使用JavaScript可以通过动态创建DOM元素并控制其CSS动画实现。
HTML结构准备
创建一个容器用于放置弹幕元素,并设置CSS样式确保弹幕能正确显示:
<div id="barrage-container" style="position: relative; width: 100%; height: 500px; overflow: hidden;"></div>
CSS样式设置
弹幕元素需要绝对定位,并添加动画效果:
.barrage-item {
position: absolute;
white-space: nowrap;
color: #fff;
font-size: 20px;
text-shadow: 1px 1px 2px #000;
animation: move linear;
}
@keyframes move {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
JavaScript实现逻辑
创建弹幕生成函数,动态插入DOM元素并设置随机位置:
function createBarrage(text) {
const container = document.getElementById('barrage-container');
const item = document.createElement('div');
item.className = 'barrage-item';
item.textContent = text;
// 随机垂直位置
const top = Math.random() * (container.offsetHeight - 30);
item.style.top = `${top}px`;
// 随机颜色
const color = `hsl(${Math.random() * 360}, 100%, 70%)`;
item.style.color = color;
// 随机动画持续时间
const duration = 5 + Math.random() * 5;
item.style.animationDuration = `${duration}s`;
container.appendChild(item);
// 动画结束后移除元素
item.addEventListener('animationend', () => {
item.remove();
});
}
弹幕发送功能
添加输入框和发送按钮实现交互:
<input type="text" id="barrage-input" placeholder="输入弹幕内容">
<button onclick="sendBarrage()">发送</button>
<script>
function sendBarrage() {
const input = document.getElementById('barrage-input');
if (input.value.trim()) {
createBarrage(input.value);
input.value = '';
}
}
</script>
高级功能扩展
实现弹幕池管理,控制同时显示的弹幕数量:
const barragePool = [];
const MAX_BARRAGE = 50;
function manageBarragePool() {
if (barragePool.length > MAX_BARRAGE) {
const oldest = barragePool.shift();
oldest.remove();
}
}
function createBarrage(text) {
// ...之前的代码...
barragePool.push(item);
manageBarragePool();
}
添加碰撞检测避免弹幕重叠:
function checkCollision(newItem) {
const newRect = newItem.getBoundingClientRect();
return barragePool.some(item => {
const rect = item.getBoundingClientRect();
return !(newRect.right < rect.left ||
newRect.left > rect.right ||
newRect.bottom < rect.top ||
newRect.top > rect.bottom);
});
}
// 在createBarrage中调用
let top = Math.random() * (container.offsetHeight - 30);
let attempts = 0;
while (attempts < 10 && checkCollision(item)) {
top = Math.random() * (container.offsetHeight - 30);
item.style.top = `${top}px`;
attempts++;
}
性能优化建议
使用Canvas渲染替代DOM操作可提升大量弹幕时的性能:
const canvas = document.getElementById('barrage-canvas');
const ctx = canvas.getContext('2d');
function drawBarrage(text, x, y) {
ctx.fillStyle = 'white';
ctx.font = '20px sans-serif';
ctx.fillText(text, x, y);
}
考虑使用requestAnimationFrame实现动画循环,替代CSS动画以获得更精确的控制。







