HTML 视频弹幕效果代码 - 用 JavaScript 实现实时弹幕动画
<!DOCTYPE html>
<html>
<head>
<title>Video Danmu</title>
<style type="text/css">
#video-container {
position: relative;
width: 640px;
height: 360px;
}
#video {
width: 100%;
height: 100%;
}
#danmu-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
overflow: hidden;
}
.danmu {
position: absolute;
font-size: 16px;
font-weight: bold;
color: white;
white-space: nowrap;
text-shadow: 1px 1px black;
pointer-events: none;
user-select: none;
will-change: transform;
animation: danmuMove linear 10s;
}
@keyframes danmuMove {
from {
transform: translateX(100%);
}
to {
transform: translateX(-100%);
}
}
</style>
</head>
<body>
<div id="video-container">
<video id="video" src="video.mp4" controls></video>
<div id="danmu-container"></div>
</div>
<pre><code><script type="text/javascript">
// 获取元素
var video = document.getElementById('video');
var danmuContainer = document.getElementById('danmu-container');
// 添加弹幕
function addDanmu(text) {
var danmu = document.createElement('div');
danmu.classList.add('danmu');
danmu.textContent = text;
danmu.style.top = randomInt(0, danmuContainer.offsetHeight - danmu.offsetHeight) + 'px';
danmu.style.animationDuration = randomInt(8, 12) + 's';
danmuContainer.appendChild(danmu);
}
// 随机整数
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// 监听视频播放事件
video.addEventListener('play', function() {
// 每200毫秒添加一个弹幕
setInterval(function() {
addDanmu('弹幕内容');
}, 200);
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/nm7e 著作权归作者所有。请勿转载和采集!