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

首頁 > 開發 > HTML5 > 正文

基于Canvas+Vue的彈幕組件的實現

2024-09-05 07:19:32
字體:
來源:轉載
供稿:網友

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

彈幕效果

 功能介紹

  • 支持循環彈幕
  • 彈幕不重疊
  • 支持選擇軌道數
  • 支持彈幕發送

使用

npm i vue-barrage

參數配置 

name type default desc
barrageList Array [] 彈幕數據
speed Number 4 彈幕滾動速度
loop Boolean true 是否循環滾動
channels Number 2 彈幕軌道數

功能實現

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實現

監聽數據源

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

數據初始化

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

/** * 數據初始化 */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)    }},/** * 增加數據 * @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, // 彈幕內容        x: x + offsetWidth, // 確定每一條彈幕的初始位置        originX: x + offsetWidth, // 存儲當前彈幕的位置,以便在循環的時候使用        position: position,        width: this.ctx.measureText(content).width * 3, // canvas繪制內容寬度        color: color || this.getColor() // 自定義顏色    })},

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

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

其他函數

/** * 獲取文字位置 * 使用pathWayIndex來確認每一條彈幕所在的軌道 * 返回距離頂部的距離 * @TODO此處還可以優化,根據每條軌道的距離來判斷下一條彈幕出現位置  */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()}

此處為彈幕服務函數

使用

<barrage    ref="barrage"    class="barrage"    :barrage-list="barrageList"    :speed="speed"    :loop="loop"    :channels="channels"/>    import Barrage from 'vue-barrage'// 彈幕數據初始化  this.barrageList = [{    content: '試數據測試數測試數據數測試數據',    color: 'white'}]// 新增彈幕this.$refs.barrage.add({    content: '增加一條新的彈幕增加一條新的彈幕', color: 'white'})

結語

總的來說這個組件還有可優化的空間,后續我會繼續改進。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 罗平县| 山阳县| 万山特区| 澳门| 泽普县| 白玉县| 崇州市| 普安县| 莲花县| 云安县| 肇源县| 克拉玛依市| 咸丰县| 雅安市| 石林| 张家口市| 泉州市| 濮阳市| 灯塔市| 基隆市| 永靖县| 堆龙德庆县| 荔浦县| 玉田县| 新田县| 鄂伦春自治旗| 华坪县| 崇礼县| 大悟县| 聂荣县| 罗城| 西丰县| 虎林市| 德令哈市| 东乡| 丘北县| 徐水县| 溆浦县| 巴塘县| 大兴区| 太康县|