originX: x + offsetWidth, // 存储当前弹幕的位置,以便在循环的时候使用
position: position,
width: this.ctx.measureText(content).width * 3, // canvas绘制内容宽度
color: color || this.getColor() // 自定义颜色
})
},
初始化数据需要处理的就是计算当前弹幕的轨道、位置、宽度,以便在
canvas 绘制的时候使用绘制
canvas
/**
* 渲染
*/
render () {
this.ctx.clearRect(0, 0, this.barrageWidth, this.barrageHeight)
this.ctx.font = '30px Microsoft YaHei'
this.draw()
window.requestAnimationFrame(this.render) // 每隔16.6毫秒渲染一次,如果使用setInterval的话在低端机型会有点卡顿
},
/**
* 开始绘制 文字和背景
*/
draw () {
for (let i = 0, len = this.barrageArray.length; i < len; i++) {
let barrage = this.barrageArray[i]try {
barrage.x -= this.speed
if (barrage.x < -barrage.width - 100) { // 此处判断弹幕消失时机
if (i === this.barrageArray.length - 1) { // 最后一条消失时的判断逻辑
if (!this.loop) { //如果不是循环弹幕的话就取消绘制 判断是否循环,不循环执行cancelAnimationFrame
cancelAnimationFrame(this.render)
return
}
if (this.addArray.length !== 0) { // 此处判断增加弹幕的逻辑
this.barrageArray = this.barrageArray.concat(this.addArray)
this.addArray = []}
for (let j = 0; j < this.barrageArray.length; j++) { // 给每条弹幕的x初始值
this.barrageArray[j].x = this.barrageArray[j].originX
}
}
}
if (barrage.x <= 2 * document.body.clientWidth + barrage.width) { // 判断什么时候开始绘制,如果不判断的话会导致弹幕滚动卡顿
// 绘制背景
this.drawRoundRect(this.ctx, barrage.x - 15, barrage.position - 30, barrage.width + 30, 40, 20, `rgba(0,0,0,0.75)`)
// 绘制文字
this.ctx.fillStyle = `${barrage.color}`
this.ctx.fillText(barrage.content, barrage.x, barrage.position)
}
} catch (e) {
console.log(e)
}
}
},此处判断绘制逻辑,包括什么时候取消,弹幕开始绘制判断,弹幕消失判断
其他函数
/**
* 获取文字位置
* 使用pathWayIndex来确认每一条弹幕所在的轨道
* 返回距离顶部的距离
* @TODO此处还可以优化,根据每条轨道的距离来判断下一条弹幕出现位置
*/
getPosition () {
let range = this.channels
let top = (this.pathWayIndex % range) * 50 + 40
this.pathWayIndex++
return top
},
/**
* 获取随机颜色
*/
getColor () {
return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
},
/**
* 绘画圆角矩形









