主頁 > 知識庫 > 基于Canvas+Vue的彈幕組件的實現(xiàn)

基于Canvas+Vue的彈幕組件的實現(xiàn)

熱門標簽:智能手機 網(wǎng)站建設(shè) 硅谷的囚徒呼叫中心 美圖手機 使用U盤裝系統(tǒng) 百度競價點擊價格的計算公式 阿里云 檢查注冊表項

最近由于項目需要定制化一個彈幕功能,所以嘗試使用canvas來開發(fā)組件。經(jīng)過測試在一些低端機的效果也沒有明顯的卡頓,和大家交流一下

彈幕效果

 功能介紹

  • 支持循環(huán)彈幕
  • 彈幕不重疊
  • 支持選擇軌道數(shù)
  • 支持彈幕發(fā)送

使用

npm i vue-barrage

參數(shù)配置 

name type default desc
barrageList Array [] 彈幕數(shù)據(jù)
speed Number 4 彈幕滾動速度
loop Boolean true 是否循環(huán)滾動
channels Number 2 彈幕軌道數(shù)

功能實現(xiàn)

html樣式

<template>
    <div class="barrage-container">
        <div
            class="container"
            :style="{height: barrageHeight/2+'px'}">
            <canvas
                id="canvas"
                ref="canvas"
                :width="barrageWidth"
                :height="barrageHeight"
                :style="{'width': barrageWidth/2 + 'px','height': barrageHeight/2 + 'px'}"/>
        </div>
    </div>
</template>

js實現(xiàn)

監(jiān)聽數(shù)據(jù)源

watch: {
    barrageList (val) {
        if (val.length !== 0) {
            this.initData() // 數(shù)據(jù)初始化
            this.render() // 開始渲染
        }
    }
}

數(shù)據(jù)初始化

barrageArray 是存儲彈幕數(shù)據(jù)用的,包括默認彈幕列表和新增彈幕項

/**
 * 數(shù)據(jù)初始化
 */
initData () {
    for (let i = 0; i < this.barrageList.length; i++) { // 此處處理只顯示40個字符
        let content = this.barrageList[i].content.length > 40 ? `${this.barrageList[i].content.substring(0, 40)}...` : this.barrageList[i].content
        this.pushMessage(content, this.barrageList[i].color)
    }
},
/**
 * 增加數(shù)據(jù)
 * @param content
 * @param color
 */
pushMessage (content, color) {
    let position = this.getPosition() // 確定跑道位置
    let x = this.barrageWidth // 初始位置
    let offsetWidth = 0
    for (let i = 0, len = this.barrageArray.length; i < len; i++) {
        let item = this.barrageArray[i]
        if (position === item.position) { // 如果同跑道,則往后排
            offsetWidth += Math.floor(this.ctx.measureText(item.content).width * 3 + 60)
        }
    }
    this.barrageArray.push({
        content: content, // 彈幕內(nèi)容
        x: x + offsetWidth, // 確定每一條彈幕的初始位置
        originX: x + offsetWidth, // 存儲當(dāng)前彈幕的位置,以便在循環(huán)的時候使用
        position: position,
        width: this.ctx.measureText(content).width * 3, // canvas繪制內(nèi)容寬度
        color: color || this.getColor() // 自定義顏色
    })
},

初始化數(shù)據(jù)需要處理的就是計算當(dāng)前彈幕的軌道、位置、寬度,以便在 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) { //如果不是循環(huán)彈幕的話就取消繪制 判斷是否循環(huán),不循環(huán)執(zhí)行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) { // 判斷什么時候開始繪制,如果不判斷的話會導(dǎo)致彈幕滾動卡頓
                // 繪制背景
                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)
        }
    }
},

此處判斷繪制邏輯,包括什么時候取消,彈幕開始繪制判斷,彈幕消失判斷

其他函數(shù)

/**
 * 獲取文字位置
 * 使用pathWayIndex來確認每一條彈幕所在的軌道
 * 返回距離頂部的距離
 * @TODO此處還可以優(yōu)化,根據(jù)每條軌道的距離來判斷下一條彈幕出現(xiàn)位置 
 */
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);
},
/**
 * 繪畫圓角矩形
 * @param context
 * @param x
 * @param y
 * @param width
 * @param height
 * @param radius
 * @param color
 */
drawRoundRect (context, x, y, width, height, radius, color) {
    context.beginPath()
    context.fillStyle = color
    context.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2)
    context.lineTo(width - radius + x, y)
    context.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2)
    context.lineTo(width + x, height + y - radius)
    context.arc(width - radius + x, height - radius + y, radius, 0, Math.PI / 2)
    context.lineTo(radius + x, height + y)
    context.arc(radius + x, height - radius + y, radius, Math.PI / 2, Math.PI)
    context.fill()
    context.closePath()
}

此處為彈幕服務(wù)函數(shù)

使用

<barrage
    ref="barrage"
    class="barrage"
    :barrage-list="barrageList"
    :speed="speed"
    :loop="loop"
    :channels="channels"/>
    
import Barrage from 'vue-barrage'

// 彈幕數(shù)據(jù)初始化  
this.barrageList = [{
    content: '試數(shù)據(jù)測試數(shù)測試數(shù)據(jù)數(shù)測試數(shù)據(jù)',
    color: 'white'
}]

// 新增彈幕
this.$refs.barrage.add({
    content: '增加一條新的彈幕增加一條新的彈幕', color: 'white'
})

結(jié)語

總的來說這個組件還有可優(yōu)化的空間,后續(xù)我會繼續(xù)改進。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

標簽:賀州 黃山 湘潭 懷化 煙臺 湖北 通遼 山南

巨人網(wǎng)絡(luò)通訊聲明:本文標題《基于Canvas+Vue的彈幕組件的實現(xiàn)》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266