国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > HTML > 正文

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

2024-08-26 00:21:34
字體:
供稿:網(wǎng)友

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

彈幕效果

 

 
Canvas,Vue,彈幕

 

 功能介紹

  • 支持循環(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ù)用的,包括默認(rèn)彈幕列表和新增彈幕項

/** * 數(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來確認(rèn)每一條彈幕所在的軌道 * 返回距離頂部的距離 * @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ù)改進(jìn)。

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


注:相關(guān)教程知識閱讀請移步到HTML教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 迭部县| 梅州市| 海伦市| 林甸县| 资讯 | 湘阴县| 东光县| 邓州市| 若尔盖县| 仁化县| 东乌珠穆沁旗| 桃园县| 临高县| 富民县| 高碑店市| 西乌| 湘潭市| 达拉特旗| 虞城县| 屯留县| 宝鸡市| 长葛市| 焦作市| 镇江市| 大渡口区| 铜川市| 贡觉县| 江源县| 邹平县| 台南市| 勃利县| 建湖县| 旬邑县| 六枝特区| 罗江县| 景德镇市| 古浪县| 建始县| 土默特左旗| 军事| 都江堰市|