實(shí)現(xiàn)B站彈幕很難么?這個(gè)開源項(xiàng)目了解一下
說起B(yǎng)站,最有特色的功能就是彈幕,現(xiàn)在彈幕已成為各大視頻網(wǎng)站的標(biāo)配,其實(shí),彈幕最早是誕生于日本的一個(gè)二次元網(wǎng)站Niconico。后來A站和B站將其引入,開啟了國內(nèi)彈幕文化的先河。
相比點(diǎn)贊、轉(zhuǎn)發(fā)、評(píng)論,彈幕的形式讓用戶的互動(dòng)性更強(qiáng),因此也更受大家喜愛,很多人已經(jīng)養(yǎng)成了看視頻必開彈幕的習(xí)慣。
假如程序員自己要實(shí)現(xiàn)一個(gè)彈幕功能會(huì)難么?已經(jīng)有人在Github上造了一個(gè)——rc-bullets。rc-bullets是一個(gè)基于 CSS3 Animation,使用 React 構(gòu)建,可擴(kuò)展,高性能的彈幕組件。
rc-bullets已經(jīng)在Github上標(biāo)星 331,累計(jì)分支 33。(詳情:https://github.com/zerosoul/rc-bullets)
rc-bullets具有以下特性:
- 支持傳入 React 組件,靈活控制彈幕內(nèi)容和 UI,并提供一個(gè)默認(rèn)樣式組件:
- 彈幕屏幕管理:清屏,暫停,隱藏(后續(xù)可能會(huì)加入針對(duì)單個(gè)彈幕的控制)
- 彈幕動(dòng)畫參數(shù)化:運(yùn)動(dòng)函數(shù)(勻速/ease/步進(jìn)/cubic-bezier)、時(shí)長(秒)、循環(huán)次數(shù)、延遲等
- 鼠標(biāo)懸浮彈幕暫停
接下來看一下彈幕效果:
安裝方式
npm:
- npm install --save rc-bullets
yarn:
- yarn add rc-bullets
初始化一個(gè)簡單的彈幕場景:
- import React, { useEffect, useState } from 'react';
- import BulletScreen, { StyledBullet } from 'rc-bullets';
- const headUrl='https://zerosoul.github.io/rc-bullets/assets/img/heads/girl.jpg';
- export default function Demo() {
- // 彈幕屏幕
- const [screen, setScreen] = useState(null);
- // 彈幕內(nèi)容
- const [bullet, setBullet] = useState('');
- useEffect(() => {
- // 給頁面中某個(gè)元素初始化彈幕屏幕,一般為一個(gè)大區(qū)塊。此處的配置項(xiàng)全局生效
- let s = new BulletScreen('.screen',{duration:20});
- // or
- // let s=new BulletScreen(document.querySelector('.screen));
- setScreen(s);
- }, []);
- // 彈幕內(nèi)容輸入事件處理
- const handleChange = ({ target: { value } }) => {
- setBullet(value);
- };
- // 發(fā)送彈幕
- const handleSend = () => {
- if (bullet) {
- // push 純文本
- screen.push(bullet);
- // or 使用 StyledBullet
- screen.push(
- <StyledBullet
- head={headUrl}
- msg={bullet}
- backgroundColor={'#fff'}
- size='large'
- />
- );
- // or 還可以這樣使用,效果等同使用 StyledBullet 組件
- screen.push({msg:bullet,head:headUrl,color:"#eee" size="large" backgroundColor:"rgba(2,2,2,.3)"})
- }
- };
- return (
- <main>
- <div className="screen" style={{ width: '100vw', height: '80vh' }}></div>
- <input value={bullet} onChange={handleChange} />
- <button onClick={handleSend}>發(fā)送</button>
- </main>
- );
- }
);}