首先是html,创建div盛放视频和输入框
<div class="div0">
<video src="./test3.mp4" controls></video>
<br>
<input type="text">
</div>
输入弹幕
var Bullet;
require(["./Bullet"],function(obj){
Bullet=obj.Bullet;
document.addEventListener("keyup",keyHandler);
})
function keyHandler(e){
if(e.keyCode!==13) return;
var input=document.querySelector("input");
if(input.value.trim().length===0) return;
var bullet=new Bullet(input.value);
bullet.appendTo(".div0");
input.value="";
}
创建弹幕
var Bullet=(function(){
function Bullet(txt){
this.elem=this.createElem(txt);
}
Bullet.prototype.speed=2;
Bullet.prototype.createElem=function(txt){
if(this.elem) return this.elem;
var div=document.createElement("div");
Object.assign(div.style,{
whiteSpace: "nowrap",
position:"absolute",
})
div.textContent=txt
return div;
}
Bullet.prototype.appendTo=function(parent){
if(typeof parent==="string") parent=document.querySelector(parent);
parent.appendChild(this.elem);
this.rect=parent.getBoundingClientRect();
Object.assign(this.elem.style,{
top:Math.random()*this.rect.height/4+"px",
left:this.rect.width+"px"
});
this.x=this.rect.width;
this.width=this.elem.offsetWidth;
TimeManager.instance.add(this);
}
Bullet.prototype.update=function(){
if(!this.width) return;
this.x-=this.speed;
this.elem.style.left=this.x+"px";
if(this.x<-this.width){
TimeManager.instance.remove(this);
this.elem.remove();
this.elem=null;
}
}
return Bullet
})();
define(["./TimeManager"],function({TimeManager}){
return {
Bullet:Bullet
}
});
单例,观察者模式
var TimeManager=(function(){
function TimeManager(){
}
TimeManager.prototype.list=[];
Object.defineProperty(TimeManager,"instance",{
enumerable:true,
get:function(){
if(!TimeManager._instance){
Object.defineProperty(TimeManager,"_instance",{
value:new TimeManager()
})
}
return TimeManager._instance;
}
})
TimeManager.prototype.add=function(elem){
if(this.list.includes(elem)) return;
this.list.push(elem);
if(this.list.length>0 && !this.ids){
this.ids=setInterval(this.update.bind(this),16);
}
}
TimeManager.prototype.remove=function(elem){
var index=this.list.indexOf(elem);
if(index<0) return;
this.list.splice(index,1);
if(this.list.length===0 && this.ids){
clearInterval(this.ids);
this.ids=undefined;
}
}
TimeManager.prototype.update=function(){
for(var i=0;i<this.list.length;i++){
if(this.list[i].update) this.list[i].update();
}
}
return TimeManager;
})();
define({
TimeManager:TimeManager
});