html5使用canvas实现弹幕功能示例

2020-04-24 19:50:21易采站长站整理

this.speed = spe
this.color = col || "#ff0"
this.content = text
this.latestTime = 0
this.width = text.length * 20
this.id = 0
this.topIndex = 0
this.occupyPos = true
this.top = 300
this.left = 0
this.setLeftValue()
this.setTopValue()
}
Caption.prototype.setTopValue = function () {
for(var i = 0 ,len = topObjs.length ; i < len ; i++){
if (topObjs[i].blank) {
this.top = topObjs[i].value
this.topIndex = i
topObjs[i].blank = false
break
}
}
}
Caption.prototype.setLeftValue = function () {
if (this.isMove) {
this.left = cavWidth
}
else {
var contentLength = this.content.length
var nowItemLeft = 420 - contentLength * 9
this.left = nowItemLeft
}
}
Caption.prototype.moving = function () {
if (this.isMove) {
this.left-=this.speed
if ( this.left + this.width < cavWidth && this.occupyPos) {
this.occupyPos = false
topObjs[this.topIndex].blank = true
}
}
else{
this.latestTime += 1
if (this.latestTime > 450) {
topObjs[this.topIndex].blank = true
}
}
}
Caption.prototype.setId = function () {
this.id = capobjId
capobjId++
}

var cap1 = new Caption( false , 1 , 0 , "小礼物走一波,双击6666。。。。")
capObjs.push(cap1)
cap1.setId()

//循环遍历数组,根据对象的属性绘制在画布上
function drawAllText () {
ctx.clearRect( 0 , 0 , cavWidth , cavHeight)
ctx.beginPath()
for(var i=0 , len = capObjs . length ; i < len ; i++ ){
ctx.fillStyle = capObjs[i].color
ctx.font = "bold 20px Courier New"
ctx.fillText( capObjs[i].content , capObjs[i].left , capObjs[i].top )
ctx.closePath()
capObjs[i].moving()
// if (capObjs[i].left < - cavWidth ) {
// capObjs.splice (i ,1)
// if excute this statement , will has fault because some item in array is null
// solution is : write a new function to refresh the array
// }
}
}

//更新数组,当对象已经超出范围的时候从数组删除这个对象
function refreshObjs(objs) {
for (var i = objs.length - 1; i >= 0; i--) {
if (objs[i].left < - cavWidth || objs[i].latestTime > 450 ) {
objs.splice(i , 1)
}

}
}

//更新保存弹幕对象的数组
function updateArray () {
var now = parseInt( video.currentTime )
for (var i = testArray.length - 1; i >= 0; i--) {
var nowItemTime = parseInt(testArray[i].time)
if ( nowItemTime == now ) {
//首次写的控制高度的方式,空间利用不充分,后来改为setTopValue中的方式
// var nowItemLeft = getLeftValue(testArray[i])
// var diffTime = Math.abs(nowItemTime - lastItemTime)
// if (diffTime < 6) {
// capHeight += 30
// capHeight = capHeight > 400 ? 20 : capHeight
// }
var temcolor = colors[testArray[i].colorIndex]var temcap = new Caption ( testArray[i].ismove , 1 , temcolor , testArray[i].content )