css弹幕制作
CSS弹幕制作方法
弹幕效果可以通过CSS动画和HTML结合实现,以下是一种常见的实现方式:
HTML结构
创建包含弹幕消息的容器和弹幕元素:
<div class="danmu-container">
<div class="danmu">第一条弹幕</div>
<div class="danmu">第二条弹幕</div>
</div>
CSS样式
设置弹幕容器和动画效果:

.danmu-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
background-color: #000;
}
.danmu {
position: absolute;
color: #fff;
font-size: 16px;
white-space: nowrap;
text-shadow: 1px 1px 2px #000;
animation: danmu-move 10s linear;
}
@keyframes danmu-move {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
动态添加弹幕
使用JavaScript动态添加弹幕元素:
function addDanmu(text) {
const container = document.querySelector('.danmu-container');
const danmu = document.createElement('div');
danmu.className = 'danmu';
danmu.textContent = text;
// 随机设置垂直位置
const top = Math.random() * (container.clientHeight - 20);
danmu.style.top = `${top}px`;
// 随机设置颜色
const color = `hsl(${Math.random() * 360}, 100%, 70%)`;
danmu.style.color = color;
// 随机设置动画持续时间
const duration = 8 + Math.random() * 5;
danmu.style.animationDuration = `${duration}s`;
container.appendChild(danmu);
// 动画结束后移除元素
danmu.addEventListener('animationend', function() {
container.removeChild(danmu);
});
}
弹幕样式优化
可以添加更多样式效果增强弹幕表现:

.danmu {
/* 基础样式 */
padding: 2px 8px;
border-radius: 12px;
background-color: rgba(0, 0, 0, 0.5);
/* 描边效果 */
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
}
弹幕碰撞检测
实现更高级的弹幕系统可以添加碰撞检测:
function isColliding(el1, el2) {
const rect1 = el1.getBoundingClientRect();
const rect2 = el2.getBoundingClientRect();
return !(
rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom
);
}
响应式调整
确保弹幕在不同屏幕尺寸下正常显示:
@media (max-width: 768px) {
.danmu {
font-size: 14px;
}
}






