弹幕实现js
弹幕实现的基本原理
弹幕功能的实现核心在于动态创建DOM元素,控制其从右向左移动,并在适当时间移除已完成动画的元素。主要涉及CSS动画、DOM操作和性能优化。
HTML结构搭建
创建一个固定定位的容器作为弹幕显示区域,通常覆盖在视频或直播画面上方:

<div id="danmu-container" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
CSS动画定义
使用CSS3动画实现平滑移动效果,性能优于JavaScript定时器:
@keyframes danmu-move {
from { transform: translateX(100vw); }
to { transform: translateX(-100%); }
}
.danmu-item {
position: absolute;
white-space: nowrap;
color: white;
text-shadow: 1px 1px 2px black;
animation: danmu-move 8s linear forwards;
}
JavaScript核心逻辑
创建弹幕元素并管理生命周期:

function createDanmu(text, options = {}) {
const item = document.createElement('div');
item.className = 'danmu-item';
item.textContent = text;
// 随机垂直位置
const top = Math.floor(Math.random() * 80);
item.style.top = `${top}%`;
// 自定义样式
if(options.color) item.style.color = options.color;
if(options.size) item.style.fontSize = options.size;
document.getElementById('danmu-container').appendChild(item);
// 动画结束后移除元素
item.addEventListener('animationend', () => {
item.remove();
});
}
性能优化方案
使用requestAnimationFrame和对象池技术减少DOM操作:
const danmuPool = [];
const activeDanmus = new Set();
function getDanmuItem() {
return danmuPool.pop() || document.createElement('div');
}
function recycleDanmu(item) {
item.style.display = 'none';
danmuPool.push(item);
}
高级功能实现
支持弹幕碰撞检测和轨道分配:
const tracks = new Array(10).fill(0);
function getAvailableTrack(width) {
for(let i = 0; i < tracks.length; i++) {
if(tracks[i] <= performance.now()) {
tracks[i] = performance.now() + (width / 100) * 8000;
return i;
}
}
return Math.floor(Math.random() * tracks.length);
}
完整调用示例
// 发送弹幕
function sendDanmu(text, options) {
const item = getDanmuItem();
// 初始化item...
const track = getAvailableTrack(item.offsetWidth);
item.style.top = `${track * 8}%`;
activeDanmus.add(item);
}
// 清理弹幕
function clearDanmu() {
activeDanmus.forEach(item => {
item.style.animation = 'none';
recycleDanmu(item);
});
activeDanmus.clear();
}
注意事项
移动端需要考虑触摸事件穿透问题,通过CSS属性pointer-events: none解决。大量弹幕时建议使用Canvas渲染替代DOM方案,性能更佳。弹幕速度应可配置,不同长度文本可采用不同动画时长。






