js做一个简单的视频弹幕原生代码
时间: 2023-06-07 13:07:31 浏览: 164
好的,以下是一个简单的视频弹幕原生代码:
HTML代码:
```
<video id="myVideo" width="100%" height="100%" controls>
<source src="video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<div id="danmu-container"></div>
<form id="danmu-form">
<input type="text" placeholder="请输入弹幕内容" id="danmu-input">
<button type="submit">发送</button>
</form>
```
CSS代码:
```
#danmu-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
pointer-events: none;
}
.danmu {
position: absolute;
top: 0;
white-space: nowrap;
font-size: 20px;
color: #fff;
text-shadow: 1px 1px 1px #000;
pointer-events: auto;
animation-duration: 10s;
animation-timing-function: linear;
}
.danmu-left {
animation-name: danmu-left;
animation-direction: normal;
}
.danmu-right {
animation-name: danmu-right;
animation-direction: reverse;
}
@keyframes danmu-left {
0% {
transform: translateX(100%);
}
100% {
transform: translateX(-100%);
}
}
@keyframes danmu-right {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(100%);
}
}
```
JavaScript代码:
```
const video = document.getElementById('myVideo');
const danmuContainer = document.getElementById('danmu-container');
const danmuForm = document.getElementById('danmu-form');
const danmuInput = document.getElementById('danmu-input');
// 监听视频播放事件
video.addEventListener('play', function() {
setInterval(() => {
// 随机生成弹幕样式、位置、速度
const danmu = document.createElement('div');
danmu.classList.add('danmu');
danmu.classList.add(Math.random() < 0.5 ? 'danmu-left' : 'danmu-right');
danmu.style.top = `${Math.floor(Math.random() * (danmuContainer.offsetHeight - 30))}px`;
danmu.style.animationDuration = `${Math.floor(Math.random() * 5 + 5)}s`
danmu.innerText = '弹幕内容';
danmuContainer.appendChild(danmu);
setTimeout(() => {
danmu.remove();
}, 10000);
}, 2000);
});
// 监听提交弹幕表单事件
danmuForm.addEventListener('submit', function(event) {
event.preventDefault();
const danmu = document.createElement('div');
danmu.classList.add('danmu');
danmu.classList.add(Math.random() < 0.5 ? 'danmu-left' : 'danmu-right');
danmu.style.top = `${Math.floor(Math.random() * (danmuContainer.offsetHeight - 30))}px`;
danmu.style.animationDuration = `${Math.floor(Math.random() * 5 + 5)}s`
danmu.innerText = danmuInput.value;
danmuContainer.appendChild(danmu);
setTimeout(() => {
danmu.remove();
}, 10000);
danmuInput.value = '';
});
```
以上代码实现了一个在视频上方随机出现的弹幕和一个文本框用于用户输入弹幕。用户输入的弹幕会随机分配样式和位置,与随机出现的弹幕相似。这个弹幕实现并不完善,它可能存在一些性能问题和兼容性问题,但它可以给你提供一个简单的思路。
阅读全文