How to implement the barrage component in native JavaScript
JavaScript column today introduces you to the method of implementing barrage components in native JavaScript.
Preface
Nowadays, almost all video websites have barrage functions, so today we will encapsulate one ourselves using native JavaScript
Barrage type. This class hopes to have the following attributes and instance methods:
Attribute
-
el
The selector of the container node. The container node should be absolutely positioned and the width and height should be set. -
height
The height of each barrage -
mode
In barrage mode, half is half the height of the container, and top is one-third. full is the time it takes for the barrage to cross the screen speed
-
gapWidth
The distance between the next barrage and the previous barrage
Method
-
pushData
Add barrage metadata -
addData
Continue to join barrages -
start
Start scheduling barrage -
stop
Stop barrage -
restart
Restart barrage -
clearData
Clear the barrage -
close
Close -
open
Redisplay the barrage
PS: There are some self-encapsulated tool functions that I won’t post here. You just need to know the meaning.
Initialization
After introducing the JavaScript file, we hope to use it as follows , first adopt the default configuration.
let barrage = new Barrage({ el: '#container'})复制代码
Parameter initialization:
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 = [] }复制代码
Accept the parameters first and then initialize them. Let’s see how getBoxSize
and 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'))) } }复制代码
pass getComputedStyle
api calculates the width and height of the box, which is used to calculate the width and height of the container and will be used later.
function initRows(box, mode, height) { let pisor = getpisor(mode) rows = Math.ceil(box.height * pisor / height) return rows }function getpisor(mode) { let pisor = .5 switch (mode) { case 'half': pisor = .5 break case 'top': pisor = 1 / 3 break; case 'full': pisor = 1; break default: break; } return pisor }复制代码
Calculate how many lines the barrage should have based on the height. The number of lines will be used somewhere below.
Insert data
There are two ways to insert data, one is to add source data, and the other is to continuously add. Let’s first look at the method of adding source data:
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节点 for (let i = 0; i < this.rows; i++) { let p = document.createElement('p') p.classList = `barrage-list barrage-list-${i}` p.style.height = `${this.boxSize.height*getpisor(this.mode)/this.rows}px` this.container.appendChild(p) } } }复制代码
this.pushOne = function (data) { for (let i = 0; i < this.rows; i++) { if (!this.list[i]) this.list[i] = [] } let leastRow = getLeastRow(this.list) //获取弹幕列表中最少的那一列,弹幕列表是一个二维数组 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 } }) }//根据行数把一维的弹幕list切分成rows行的二维数组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 }复制代码
The method of continuously adding data is just to call the method of adding source data and start scheduling
this.addData = function (data) { this.pushData(data) this.start() }复制代码
Launch barrages
Let’s take a look at the logic of launching barrages
this.start = function () { //开始调度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 } //真正的调度从这里开始,用一个实例变量存储好当前调度的下标。 if (row[this.indexs[i]]) { this.dispatchItem(row[this.indexs[i]], i, this.indexs[i]) } }复制代码
this.dispatchItem = function (item, i) { //调度过一次的某条弹幕下一次在调度就不需要了 if (!item || this.idMap[item.id]) { return } let index = this.indexs[i] this.idMap[item.id] = item.id let p = document.createElement('p'), parent = document.querySelector(`${el} .barrage-list-${i}`), width, pastTime p.innerHTML = item.content p.className = 'barrage-item' parent.appendChild(p) width = getBoxSize(p).width p.style = `width:${width}px;display:none` pastTime = this.computeTime(width) //计算出下一条弹幕应该出现的时间 //弹幕飞一会~ this.run(p) if (index > this.list[i].length - 1) { return } let len = this.timeoutFuncs.length //记录好定时器,后面清空 this.timeoutFuncs[len] = setTimeout(() => { this.indexs[i] = index + 1 //递归调用下一条 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` //已完成的打一个标记 setTimeout(() => { item.classList+=' done' }, this.speed); }复制代码
//根据弹幕的宽度和gapWth,算出下一条弹幕应该出现的时间this.computeTime = function (width) { let length = width + this.gapWidth let time = Math.round(length / this.boxSize.width * this.speed/2) return time }复制代码
The animation css is as follows
@keyframes run { 0% { left: 100%; } 50% { left: 0 } 100% { left: -100%; } }.run { animation-name: run; }复制代码
Other methods
Stop
Use the paused attribute of the animation to stop
this.stop = function () { let items = document.querySelectorAll(`${el} .barrage-item`); [...items].forEach(item => { item.className += ' pause' }) }复制代码
.pause { animation-play-state: paused !important; }复制代码
Start again
Remove the pause class
this.restart = function () { let items = document.querySelectorAll(`${el} .barrage-item`); [...items].forEach(item => { removeClassName(item, 'pause') }) }复制代码
Open and close
Just make a show-hidden logic
this.close = function () { this.container.style.display = 'none'}this.open = function () { this.container.style.display = ''}复制代码
Clean up the barrages
this.clearData = function () { //清除list this.list = [] //清除dom document.querySelector(`${el}`).innerHTML = '' //清除timeout this.timeoutFuncs.forEach(fun => clearTimeout(fun)) }复制代码
Finally, use a timer to clean up the expired barrages:
setInterval(() => { let items = document.querySelectorAll(`${el} .done`); [...items].forEach(item=>{ item.parentNode.removeChild(item) }) }, this.speed*5);复制代码
Finally
I feel that the implementation of this is still flawed. If you designed it like this How would you design a class?
Related free learning recommendations: javascript(Video)
The above is the detailed content of How to implement the barrage component in native JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

In the software Youku, we can freely turn on and off the barrage, and we can also adjust the display settings of the barrage. Some users don’t know where Youku’s barrage settings are. The article introduces how to set up the mobile phone and computer. The editor below will introduce you to the barrage setting method. Let’s take a look at this article. Where to set up the Youku barrage mobile version? 1. Enter any Youku video, click on the middle of the video, and then click on the full screen on the lower right. 2. Click in the middle of the video again and click on the three dots on the upper right. 3. You can see [Barrage Settings] on the upper right. 4. Click to enter to set up the barrage display. PC version 1. Enter Youku and select any video. 2. In the line below the video, you can see the [pop-up] of the settings icon in the lower right corner. 3. Click to play
