溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Vue中使用Canvas實(shí)現(xiàn)一個(gè)彈幕組件

發(fā)布時(shí)間:2021-04-16 17:08:15 來源:億速云 閱讀:474 作者:Leah 欄目:web開發(fā)

本篇文章為大家展示了怎么在Vue中使用Canvas實(shí)現(xiàn)一個(gè)彈幕組件,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

功能介紹

  • 支持循環(huán)彈幕

  • 彈幕不重疊

  • 支持選擇軌道數(shù)

  • 支持彈幕發(fā)送

使用

npm i vue-barrage

參數(shù)配置 

nametypedefaultdesc
barrageListArray[]彈幕數(shù)據(jù)
speedNumber4彈幕滾動(dòng)速度
loopBooleantrue是否循環(huán)滾動(dòng)
channelsNumber2彈幕軌道數(shù)

功能實(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實(shí)現(xiàn)

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

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

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

barrageArray 是存儲(chǔ)彈幕數(shù)據(jù)用的,包括默認(rèn)彈幕列表和新增彈幕項(xiàng)

/**
 * 數(shù)據(jù)初始化
 */
initData () {
    for (let i = 0; i < this.barrageList.length; i++) { // 此處處理只顯示40個(gè)字符
        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, // 存儲(chǔ)當(dāng)前彈幕的位置,以便在循環(huán)的時(shí)候使用
        position: position,
        width: this.ctx.measureText(content).width * 3, // canvas繪制內(nèi)容寬度
        color: color || this.getColor() // 自定義顏色
    })
},

初始化數(shù)據(jù)需要處理的就是計(jì)算當(dāng)前彈幕的軌道、位置、寬度,以便在 canvas 繪制的時(shí)候使用

繪制 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的話在低端機(jī)型會(huì)有點(diǎn)卡頓
},
/**
 * 開始繪制 文字和背景
 */
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) { // 此處判斷彈幕消失時(shí)機(jī)
                if (i === this.barrageArray.length - 1) { // 最后一條消失時(shí)的判斷邏輯
                    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) { // 判斷什么時(shí)候開始繪制,如果不判斷的話會(huì)導(dǎo)致彈幕滾動(dòng)卡頓
                // 繪制背景
                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í)候取消,彈幕開始繪制判斷,彈幕消失判斷

其他函數(shù)

/**
 * 獲取文字位置
 * 使用pathWayIndex來確認(rèn)每一條彈幕所在的軌道
 * 返回距離頂部的距離
 * @TODO此處還可以優(yōu)化,根據(jù)每條軌道的距離來判斷下一條彈幕出現(xiàn)位置 
 */
getPosition () {
    let range = this.channels
    let top = (this.pathWayIndex % range) * 50 + 40
    this.pathWayIndex++
    return top
},
/**
 * 獲取隨機(jī)顏色
 */
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'
})

上述內(nèi)容就是怎么在Vue中使用Canvas實(shí)現(xiàn)一個(gè)彈幕組件,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI