原生JavaScript实现弹幕组件的方法

 4541

原生JavaScript实现弹幕组件的方法


前言

如今几乎所有的视频网站都有弹幕功能,那么今天我们就自己用原生 JavaScript 封装一个弹幕类。这个类希望有如下属性和实例方法:

属性

el容器节点的选择器,容器节点应为绝对定位,设置好宽高

height 每条弹幕的高度

mode 弹幕模式,half则为一半容器高度,top为三分之一,full为占满

speed弹幕划过屏幕的时间

gapWidth后一条弹幕与前一条弹幕的距离

方法

pushData 添加弹幕元数据

addData持续加入弹幕

start开始调度弹幕

stop停止弹幕

restart 重新开始弹幕

clearData清空弹幕

close关闭

open重新显示弹幕


PS:有一些自封装的工具函数就不贴出来了,大概知道意思就好

初始化

引入JavaScript文件之后,我们希望如下使用,先采取默认配置。

  1. let barrage = new Barrage({
  2.     el: '#container'
  3. })

参数初始化:

  1. function Barrage(options) {
  2.     let {
  3.         el,
  4.         height,
  5.         mode,
  6.         speed,
  7.         gapWidth,
  8.     } = options
  9.     this.container = document.querySelector(el)
  10.     this.height = height || 30
  11.     this.speed = speed || 15000 //2000ms
  12.     this.gapWidth = gapWidth || 20
  13.     this.list = []
  14.     this.mode = mode || 'half'
  15.     this.boxSize = getBoxSize(this.container)
  16.     this.perSpeed = Math.round(this.boxSize.width / this.speed)
  17.     this.rows = initRows(this.boxSize, this.mode, this.height)
  18.     this.timeoutFuncs = []
  19.     this.indexs = []
  20.     this.idMap = []
  21. }

先接受好参数然后初始化,下面看看 getBoxSize 和 initRows

  1. function getBoxSize(box) {
  2.     let {
  3.         height,
  4.         width
  5.     } = window.getComputedStyle(box)
  6.     return {
  7.         height: px2num(height),
  8.         width: px2num(width)
  9.     }
  10.     function px2num(str) {
  11.         return Number(str.substring(0, str.indexOf('p')))
  12.     }
  13. }

通过 getComputedStyleapi 计算出盒子的宽高,这里用来计算容器的宽高,之后也会用到。

  1. function initRows(box, mode, height) {
  2.     let divisor = getDivisor(mode)
  3.     rows = Math.ceil(box.height * divisor / height)
  4.     return rows
  5. }
  6. function getDivisor(mode) {
  7.     let divisor = .5
  8.     switch (mode) {
  9.         case 'half':
  10.             divisor = .5
  11.             break
  12.         case 'top':
  13.             divisor = 1 / 3
  14.             break;
  15.         case 'full':
  16.             divisor = 1;
  17.             break
  18.         default:
  19.             break;
  20.     }
  21.     return divisor
  22. }

根据高度算出弹幕应该有多少行,下面会有地方用到行数。

插入数据

有两种插入数据的方法,一种是添加源数据,一种是持续添加。先来看添加源数据的方法:

  1. this.pushData = function (data) {
  2.     this.initDom()
  3.     if (getType(data) == '[object Object]') {
  4.         //插入单条
  5.         this.pushOne(data)
  6.     }
  7.     if (getType(data) == '[object Array]') {
  8.         //插入多条
  9.         this.pushArr(data)
  10.     }
  11. }
  12. this.initDom = function () {
  13.     if (!document.querySelector(`${el} .barrage-list`)) {
  14.         //注册dom节点
  15.         for (let i = 0; i < this.rows; i++) {
  16.             let div = document.createElement('div')
  17.             div.classList = `barrage-list barrage-list-${i}`
  18.             div.style.height = `${this.boxSize.height*getDivisor(this.mode)/this.rows}px`
  19.             this.container.appendChild(div)
  20.         }
  21.     }
  22. }
  1. this.pushOne = function (data) {
  2.     for (let i = 0; i < this.rows; i++) {
  3.         if (!this.list[i]) this.list[i] = []
  4.     }
  5.     let leastRow = getLeastRow(this.list) //获取弹幕列表中最少的那一列,弹幕列表是一个二维数组
  6.     this.list[leastRow].push(data)
  7. }
  8. this.pushArr = function (data) {
  9.     let list = sliceRowList(this.rows, data)
  10.     list.forEach((item, index) => {
  11.         if (this.list[index]) {
  12.             this.list[index] = this.list[index].concat(...item)
  13.         } else {
  14.             this.list[index] = item
  15.         }
  16.     })
  17. }
  18. //根据行数把一维的弹幕list切分成rows行的二维数组
  19. function sliceRowList(rows, list) {
  20.     let sliceList = [],
  21.         perNum = Math.round(list.length / rows)
  22.     for (let i = 0; i < rows; i++) {
  23.         let arr = []
  24.         if (== rows - 1) {
  25.             arr = list.slice(* perNum)
  26.         } else {
  27.             i == 0 ? arr = list.slice(0, perNum) : arr = list.slice(* perNum, (+ 1) * perNum)
  28.         }
  29.         sliceList.push(arr)
  30.     }
  31.     return sliceList
  32. }

持续加入数据的方法只是调用了添加源数据的方法,并且开始了调度而已

  1. this.addData = function (data) {
  2.     this.pushData(data)
  3.     this.start()
  4. }

发射弹幕

下面来看看发射弹幕的逻辑

  1. this.start = function () {
  2.     //开始调度list
  3.     this.dispatchList(this.list)
  4. }
  5. this.dispatchList = function (list) {
  6.     for (let i = 0; i < list.length; i++) {
  7.         this.dispatchRow(list[i], i)
  8.     }
  9. }
  10. this.dispatchRow = function (row, i) {
  11.     if (!this.indexs[i] && this.indexs[i] !== 0) {
  12.         this.indexs[i] = 0
  13.     }
  14.     //真正的调度从这里开始,用一个实例变量存储好当前调度的下标。
  15.     if (row[this.indexs[i]]) {
  16.         this.dispatchItem(row[this.indexs[i]], i, this.indexs[i])
  17.     }
  18. }
  1. this.dispatchItem = function (item, i) {
  2.     //调度过一次的某条弹幕下一次在调度就不需要了
  3.     if (!item || this.idMap[item.id]) {
  4.         return
  5.     }
  6.     let index = this.indexs[i]
  7.     this.idMap[item.id] = item.id
  8.     let div = document.createElement('div'),
  9.         parent = document.querySelector(`${el} .barrage-list-${i}`),
  10.         width,
  11.         pastTime
  12.     div.innerHTML = item.content
  13.     div.className = 'barrage-item'
  14.     parent.appendChild(div)
  15.     width = getBoxSize(div).width
  16.     div.style = `width:${width}px;display:none`
  17.     pastTime = this.computeTime(width) //计算出下一条弹幕应该出现的时间
  18.     //弹幕飞一会~
  19.     this.run(div)
  20.     if (index > this.list[i].length - 1) {
  21.         return
  22.     }
  23.     let len = this.timeoutFuncs.length
  24.     //记录好定时器,后面清空
  25.     this.timeoutFuncs[len] = setTimeout(() => {
  26.         this.indexs[i] = index + 1
  27.         //递归调用下一条
  28.         this.dispatchItem(this.list[i][index + 1], i, index + 1)
  29.     }, pastTime);
  30. }
  1. //用css动画,整体还是比较流畅的
  2. this.run = function (item) {
  3.     item.classList += ' running'
  4.     item.style.left = "left:100%"
  5.     item.style.display = ''
  6.     item.style.animation = `run ${this.speed/1000}s linear`
  7.     //已完成的打一个标记
  8.     setTimeout(() => {
  9.         item.classList+=' done'
  10.     }, this.speed);
  11. }
  1. //根据弹幕的宽度和gapWth,算出下一条弹幕应该出现的时间
  2. this.computeTime = function (width) {
  3.     let length = width + this.gapWidth
  4.     let time = Math.round(length / this.boxSize.width * this.speed/2)
  5.     return time
  6. }

动画css具体如下

  1. @keyframes run {
  2.     0% {
  3.         left: 100%;
  4.     }
  5.     50% {
  6.         left: 0
  7.     }
  8.     100% {
  9.         left: -100%;
  10.     }
  11. }
  12. .run {
  13.     animation-name: run;
  14. }

其余方法

停止:利用动画的paused属性停止

  1. this.stop = function () {
  2.     let items = document.querySelectorAll(`${el} .barrage-item`);
  3.     [...items].forEach(item => {
  4.         item.className += ' pause'
  5.     })
  6. }
  1. .pause {
  2.     animation-play-state: paused !important;
  3. }

重新开始

移除pause类即可

  1. this.restart = function () {
  2.     let items = document.querySelectorAll(`${el} .barrage-item`);
  3.     [...items].forEach(item => {
  4.         removeClassName(item, 'pause')
  5.     })
  6. }

打开关闭

做一个显示隐藏的逻辑即可

  1. this.close = function () {
  2.     this.container.style.display = 'none'
  3. }
  4. this.open = function () {
  5.     this.container.style.display = ''
  6. }

清理弹幕

  1. this.clearData = function () {
  2.     //清除list
  3.     this.list = []
  4.     //清除dom
  5.     document.querySelector(`${el}`).innerHTML = ''
  6.     //清除timeout
  7.     this.timeoutFuncs.forEach(fun => clearTimeout(fun))
  8. }

最后用一个定时器定时清理过期的弹幕:

  1. setInterval(() => {
  2.     let items = document.querySelectorAll(`${el} .done`);
  3.     [...items].forEach(item=>{
  4.         item.parentNode.removeChild(item)
  5.     })
  6. }, this.speed*5);

最后

感觉这个的实现还是有缺陷的,如果是你设计这么一个类,你会怎么设计呢?



本文网址:https://www.zztuku.com/index.php/detail-7961.html
站长图库 - 原生JavaScript实现弹幕组件的方法
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐