js 实现弹幕
实现弹幕的基本思路
弹幕的核心功能是在屏幕上随机位置显示移动的文字或图片,通常从右向左移动。实现弹幕需要考虑元素的创建、位置随机化、动画控制以及性能优化。
HTML 结构准备
创建一个容器用于承载弹幕元素,通常使用绝对定位的 div。

<div id="danmu-container" style="position: relative; width: 100%; height: 300px; overflow: hidden;"></div>
CSS 样式设置
弹幕元素需要绝对定位,并设置合适的样式确保可读性和美观。
.danmu-item {
position: absolute;
white-space: nowrap;
font-size: 16px;
color: #fff;
text-shadow: 1px 1px 2px #000;
}
JavaScript 弹幕逻辑
弹幕的实现主要包括创建弹幕元素、设置初始位置和动画效果。

// 弹幕数据
const danmuList = ['弹幕1', '弹幕2', '弹幕3', '弹幕4', '弹幕5'];
// 获取容器
const container = document.getElementById('danmu-container');
// 创建弹幕函数
function createDanmu(text) {
const danmu = document.createElement('div');
danmu.className = 'danmu-item';
danmu.textContent = text;
// 随机设置垂直位置
const top = Math.random() * (container.clientHeight - 20);
danmu.style.top = `${top}px`;
// 初始位置在容器右侧
danmu.style.left = `${container.clientWidth}px`;
// 添加到容器
container.appendChild(danmu);
// 动画效果
const duration = 5000 + Math.random() * 3000; // 随机动画时间
const start = performance.now();
function animate(time) {
const elapsed = time - start;
const progress = elapsed / duration;
const left = container.clientWidth - (container.clientWidth * progress);
danmu.style.left = `${left}px`;
if (progress < 1) {
requestAnimationFrame(animate);
} else {
container.removeChild(danmu);
}
}
requestAnimationFrame(animate);
}
// 定时生成弹幕
setInterval(() => {
const randomText = danmuList[Math.floor(Math.random() * danmuList.length)];
createDanmu(randomText);
}, 1000);
性能优化建议
频繁创建和销毁 DOM 元素会影响性能,可以考虑使用对象池技术复用弹幕元素。
// 弹幕对象池
const danmuPool = [];
function getDanmuFromPool(text) {
let danmu = danmuPool.pop();
if (!danmu) {
danmu = document.createElement('div');
danmu.className = 'danmu-item';
}
danmu.textContent = text;
return danmu;
}
function returnDanmuToPool(danmu) {
danmuPool.push(danmu);
}
高级功能扩展
可以增加弹幕颜色、大小、速度的随机化,以及用户输入弹幕的功能。
// 随机颜色生成
function getRandomColor() {
return `hsl(${Math.random() * 360}, 100%, 50%)`;
}
// 修改createDanmu函数
danmu.style.color = getRandomColor();
danmu.style.fontSize = `${14 + Math.random() * 10}px`;
注意事项
弹幕数量过多时需要控制频率,避免浏览器卡顿。可以使用防抖或节流技术优化性能。






