原生JavaScript實(shí)現(xiàn)彈幕組件的示例代碼
前言
如今幾乎所有的視頻網(wǎng)站都有彈幕功能,那么今天我們就自己用原生 JavaScript 封裝一個(gè)彈幕類。這個(gè)類希望有如下屬性和實(shí)例方法:
屬性
- el容器節(jié)點(diǎn)的選擇器,容器節(jié)點(diǎn)應(yīng)為絕對定位,設(shè)置好寬高
- height 每條彈幕的高度
- mode 彈幕模式,half則為一半容器高度,top為三分之一,full為占滿
- speed彈幕劃過屏幕的時(shí)間
- gapWidth后一條彈幕與前一條彈幕的距離
方法
- pushData 添加彈幕元數(shù)據(jù)
- addData持續(xù)加入彈幕
- start開始調(diào)度彈幕
- stop停止彈幕
- restart 重新開始彈幕
- clearData清空彈幕
- close關(guān)閉
- open重新顯示彈幕
PS:有一些自封裝的工具函數(shù)就不貼出來了,大概知道意思就好
初始化
引入JavaScript文件之后,我們希望如下使用,先采取默認(rèn)配置。
let barrage = new Barrage({
el: '#container'
})
參數(shù)初始化:
function Barrage(options) {
let {
el,
height,
mode,
speed,
gapWidth,
} = options
this.container = document.querySelector(el)
this.height = height || 30
this.speed = speed || 15000 //2000ms
this.gapWidth = gapWidth || 20
this.list = []
this.mode = mode || 'half'
this.boxSize = getBoxSize(this.container)
this.perSpeed = Math.round(this.boxSize.width / this.speed)
this.rows = initRows(this.boxSize, this.mode, this.height)
this.timeoutFuncs = []
this.indexs = []
this.idMap = []
}
先接受好參數(shù)然后初始化,下面看看getBoxSize和initRows
function getBoxSize(box) {
let {
height,
width
} = window.getComputedStyle(box)
return {
height: px2num(height),
width: px2num(width)
}
function px2num(str) {
return Number(str.substring(0, str.indexOf('p')))
}
}
通過getComputedStyleapi計(jì)算出盒子的寬高,這里用來計(jì)算容器的寬高,之后也會用到。
function initRows(box, mode, height) {
let divisor = getDivisor(mode)
rows = Math.ceil(box.height * divisor / height)
return rows
}
function getDivisor(mode) {
let divisor = .5
switch (mode) {
case 'half':
divisor = .5
break
case 'top':
divisor = 1 / 3
break;
case 'full':
divisor = 1;
break
default:
break;
}
return divisor
}
根據(jù)高度算出彈幕應(yīng)該有多少行,下面會有地方用到行數(shù)。
插入數(shù)據(jù)
有兩種插入數(shù)據(jù)的方法,一種是添加源數(shù)據(jù),一種是持續(xù)添加。先來看添加源數(shù)據(jù)的方法:
this.pushData = function (data) {
this.initDom()
if (getType(data) == '[object Object]') {
//插入單條
this.pushOne(data)
}
if (getType(data) == '[object Array]') {
//插入多條
this.pushArr(data)
}
}
this.initDom = function () {
if (!document.querySelector(`${el} .barrage-list`)) {
//注冊dom節(jié)點(diǎn)
for (let i = 0; i < this.rows; i++) {
let div = document.createElement('div')
div.classList = `barrage-list barrage-list-${i}`
div.style.height = `${this.boxSize.height*getDivisor(this.mode)/this.rows}px`
this.container.appendChild(div)
}
}
}
this.pushOne = function (data) {
for (let i = 0; i < this.rows; i++) {
if (!this.list[i]) this.list[i] = []
}
let leastRow = getLeastRow(this.list) //獲取彈幕列表中最少的那一列,彈幕列表是一個(gè)二維數(shù)組
this.list[leastRow].push(data)
}
this.pushArr = function (data) {
let list = sliceRowList(this.rows, data)
list.forEach((item, index) => {
if (this.list[index]) {
this.list[index] = this.list[index].concat(...item)
} else {
this.list[index] = item
}
})
}
//根據(jù)行數(shù)把一維的彈幕list切分成rows行的二維數(shù)組
function sliceRowList(rows, list) {
let sliceList = [],
perNum = Math.round(list.length / rows)
for (let i = 0; i < rows; i++) {
let arr = []
if (i == rows - 1) {
arr = list.slice(i * perNum)
} else {
i == 0 ? arr = list.slice(0, perNum) : arr = list.slice(i * perNum, (i + 1) * perNum)
}
sliceList.push(arr)
}
return sliceList
}
持續(xù)加入數(shù)據(jù)的方法只是調(diào)用了添加源數(shù)據(jù)的方法,并且開始了調(diào)度而已
this.addData = function (data) {
this.pushData(data)
this.start()
}
發(fā)射彈幕
下面來看看發(fā)射彈幕的邏輯
this.start = function () {
//開始調(diào)度list
this.dispatchList(this.list)
}
this.dispatchList = function (list) {
for (let i = 0; i < list.length; i++) {
this.dispatchRow(list[i], i)
}
}
this.dispatchRow = function (row, i) {
if (!this.indexs[i] && this.indexs[i] !== 0) {
this.indexs[i] = 0
}
//真正的調(diào)度從這里開始,用一個(gè)實(shí)例變量存儲好當(dāng)前調(diào)度的下標(biāo)。
if (row[this.indexs[i]]) {
this.dispatchItem(row[this.indexs[i]], i, this.indexs[i])
}
}
this.dispatchItem = function (item, i) {
//調(diào)度過一次的某條彈幕下一次在調(diào)度就不需要了
if (!item || this.idMap[item.id]) {
return
}
let index = this.indexs[i]
this.idMap[item.id] = item.id
let div = document.createElement('div'),
parent = document.querySelector(`${el} .barrage-list-${i}`),
width,
pastTime
div.innerHTML = item.content
div.className = 'barrage-item'
parent.appendChild(div)
width = getBoxSize(div).width
div.style = `width:${width}px;display:none`
pastTime = this.computeTime(width) //計(jì)算出下一條彈幕應(yīng)該出現(xiàn)的時(shí)間
//彈幕飛一會~
this.run(div)
if (index > this.list[i].length - 1) {
return
}
let len = this.timeoutFuncs.length
//記錄好定時(shí)器,后面清空
this.timeoutFuncs[len] = setTimeout(() => {
this.indexs[i] = index + 1
//遞歸調(diào)用下一條
this.dispatchItem(this.list[i][index + 1], i, index + 1)
}, pastTime);
}
//用css動畫,整體還是比較流暢的
this.run = function (item) {
item.classList += ' running'
item.style.left = "left:100%"
item.style.display = ''
item.style.animation = `run ${this.speed/1000}s linear`
//已完成的打一個(gè)標(biāo)記
setTimeout(() => {
item.classList+=' done'
}, this.speed);
}
//根據(jù)彈幕的寬度和gapWth,算出下一條彈幕應(yīng)該出現(xiàn)的時(shí)間
this.computeTime = function (width) {
let length = width + this.gapWidth
let time = Math.round(length / this.boxSize.width * this.speed/2)
return time
}
動畫css具體如下
@keyframes run {
0% {
left: 100%;
}
50% {
left: 0
}
100% {
left: -100%;
}
}
.run {
animation-name: run;
}
其余方法
停止
利用動畫的paused屬性停止
this.stop = function () {
let items = document.querySelectorAll(`${el} .barrage-item`);
[...items].forEach(item => {
item.className += ' pause'
})
}
.pause {
animation-play-state: paused !important;
}
重新開始
移除pause類即可
this.restart = function () {
let items = document.querySelectorAll(`${el} .barrage-item`);
[...items].forEach(item => {
removeClassName(item, 'pause')
})
}
打開關(guān)閉
做一個(gè)顯示隱藏的邏輯即可
this.close = function () {
this.container.style.display = 'none'
}
this.open = function () {
this.container.style.display = ''
}
清理彈幕
this.clearData = function () {
//清除list
this.list = []
//清除dom
document.querySelector(`${el}`).innerHTML = ''
//清除timeout
this.timeoutFuncs.forEach(fun => clearTimeout(fun))
}
最后用一個(gè)定時(shí)器定時(shí)清理過期的彈幕:
setInterval(() => {
let items = document.querySelectorAll(`${el} .done`);
[...items].forEach(item=>{
item.parentNode.removeChild(item)
})
}, this.speed*5);
最后
感覺這個(gè)的實(shí)現(xiàn)還是有缺陷的,如果是你設(shè)計(jì)這么一個(gè)類,你會怎么設(shè)計(jì)呢?
到此這篇關(guān)于原生JavaScript實(shí)現(xiàn)彈幕組件的示例代碼的文章就介紹到這了,更多相關(guān)JavaScript 彈幕組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談js中Object.create()與new的具體實(shí)現(xiàn)與區(qū)別
本文主要介紹了js中Object.create()與new的具體實(shí)現(xiàn)與區(qū)別,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
高性能JavaScript模板引擎實(shí)現(xiàn)原理詳解
這篇文章主要介紹了JavaScript模板引擎實(shí)現(xiàn)原理詳解,本文著重講解artTemplate模板的實(shí)現(xiàn)原理,它采用預(yù)編譯方式讓性能有了質(zhì)的飛躍,是其它知名模板引擎的25、32 倍,需要的朋友可以參考下2015-02-02
微信小程序出現(xiàn)wx.getLocation再次授權(quán)問題的解決方法分析
這篇文章主要介紹了微信小程序出現(xiàn)wx.getLocation再次授權(quán)問題的解決方法,結(jié)合實(shí)例形式分析了解決wx.getLocation再次授權(quán)問題的相關(guān)操作步驟,需要的朋友可以參考下2019-01-01

