pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

html5使用canvas實現彈幕功能示例

這篇文章主要介紹了html5使用canvas實現彈幕功能示例的相關資料,需要的朋友可以參考下

最近在著手開發彈幕視頻網站,通過html5中的canvas實現了彈幕的功能。

那么閑言碎語不要講,先說思路后上代碼。

思路:從頁面布局上來說就是將一塊畫布覆蓋在了video標簽產生的視頻窗口之上,使用絕對定位就能實現了。最重要的就是js控制畫布上彈幕的顯示了,每一個彈幕都包裝成一個對象,對象包含的屬性有彈幕應該出現的時間,彈幕的顏色,彈幕是否是移動的以及彈幕的文本。彈幕對象擁有方法包含:設置彈幕的橫縱坐標,彈幕的移動函數。實現的原理,在監聽視頻開始播放的事件,在視頻開始播放時生成一個定時器,定時器每隔一個時間去遍歷循環彈幕對象數組并根據對象的屬性在畫布的適當位置上繪制出彈幕,計時器中除了繪制彈幕的代碼還有執行更新彈幕數組的代碼。

下圖是彈幕效果截屏

html5使用canvas實現彈幕功能示例

那么下面開始直接上代碼:

(function () {
    window.onload=function () {
        var video = document.getElementsByTagName("video")[0]
        var cav = document.getElementsByTagName("canvas")[0]
        //設置常量canvas的高度以及寬度
        var cavWidth = 800 
        var cavHeight = 420
        cav.width=cavWidth
        cav.height=cavHeight 
        var ctx = cav.getContext("2d")
        //存儲彈幕對象的數組
        var capObjs = []
        var lastItemTime
        var capHeight = 20 
        var inputEle = document.getElementsByClassName("caption-input-text")[0]
        var sendEle = document.getElementsByClassName("caption-sendButton")[0]
        var colorUl = document.getElementsByClassName("colorItems")[0]
        var ismoveInputEle = document.getElementsByClassName("caption-input-ismove")[0]
        //彈幕顏色
        var colors=["#fff","#FFCCCC","#CCFFCC","#CCCCFF","#FFFFCC","#CCFFFF"]
        var selectedColorIndex = 0
        var prevPlayTime = 0
        //測試數據的數組
        var testArrayCopy = []
        var capobjId = 0
        //彈幕在畫布中高度可能值組成的數組
        var topObjs = [{blank:true , value : 20 ,index:0},
                        {blank:true , value : 50 ,index:1},
                        {blank:true , value : 80 ,index:2},
                        {blank:true , value : 110 ,index:3},
                        {blank:true , value : 140 ,index:4},
                        {blank:true , value : 170 ,index:5},
                        {blank:true , value : 200 ,index:6},
                        {blank:true , value : 230 ,index:7},
                        {blank:true , value : 260 ,index:8},
                        {blank:true , value : 290 ,index:9},
                        {blank:true , value : 320 ,index:10},
                        {blank:true , value : 350 ,index:11},
                        {blank:true , value : 380 ,index:12},
                        {blank:true , value : 410 ,index:13}]
//test data 測試數據
var testArray = [{content:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",time:"1",ismove:false,colorIndex:0},
{content:"233333333333333",time:"2",ismove:true,colorIndex:0},
{content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:5},
{content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:4},
{content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:4},
{content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:0},
{content:"干杯,哈哈哈~~~~~~",time:"2",ismove:true,colorIndex:0},
{content:"233333333333333",time:"3",ismove:true,colorIndex:0},
{content:"233333333333333",time:"3",ismove:true,colorIndex:0},
{content:"233333333333333",time:"3",ismove:true,colorIndex:0},
{content:"233333333333333",time:"3",ismove:true,colorIndex:0},
{content:"233333333333333",time:"3",ismove:true,colorIndex:0},
{content:"233333333333333",time:"3",ismove:true,colorIndex:0},
{content:"233333333333333",time:"4",ismove:false,colorIndex:0},
{content:"233333333333333",time:"5",ismove:true,colorIndex:4},
{content:"233333333333333",time:"6",ismove:true,colorIndex:2},
{content:"233333333333333",time:"7",ismove:true,colorIndex:2},
{content:"233333333333333",time:"7",ismove:true,colorIndex:2},
{content:"233333333333333",time:"7",ismove:true,colorIndex:2},
{content:"233333333333333",time:"7",ismove:true,colorIndex:2},
{content:"233333333333333",time:"7",ismove:true,colorIndex:2},
{content:"233333333333333",time:"7",ismove:true,colorIndex:2},
{content:"233333333333333",time:"8",ismove:true,colorIndex:0},
{content:"233333333333333",time:"9",ismove:true,colorIndex:0},
{content:"233333333333333",time:"10",ismove:true,colorIndex:0},
{content:"老師說的非常好,我要好好學習了》》》》",time:"12",ismove:true,colorIndex:0},
{content:"老師說的非常好,我要好好學習了》》》》",time:"13",ismove:true,colorIndex:0},
{content:"老師說的非常好,我要好好學習了》》》》",time:"14",ismove:true,colorIndex:2},
{content:"老師說的非常好,我要好好學習了》》》》",time:"15",ismove:false,colorIndex:0},
{content:"老師說的非常好,我要好好學習了》》》》",time:"16",ismove:true,colorIndex:2},
{content:"老師說的非常好,我要好好學習了》》》》",time:"17",ismove:true,colorIndex:3},
{content:"老師說的非常好,我要好好學習了》》》》",time:"18",ismove:true,colorIndex:2},
{content:"老師說的非常好,我要好好學習了》》》》",time:"19",ismove:true,colorIndex:0},
{content:"老師說的非常好,我要好好學習了》》》》",time:"20",ismove:true,colorIndex:3},
{content:"老師說的非常好,我要好好學習了》》》》",time:"21",ismove:true,colorIndex:0},
{content:"老師說的非常好,我要好好學習了》》》》",time:"22",ismove:true,colorIndex:0},
{content:"老鐵們,小禮物走一波了,小汽車小火箭刷起來吧=========",time:"23",ismove:true,colorIndex:0},
{content:"老鐵們,小禮物走一波了,小汽車小火箭刷起來吧=========",time:"24",ismove:true,colorIndex:0},
{content:"老鐵們,小禮物走一波了,小汽車小火箭刷起來吧=========",time:"25",ismove:true,colorIndex:3},
{content:"老鐵們,小禮物走一波了,小汽車小火箭刷起來吧=========",time:"26",ismove:true,colorIndex:0},
{content:"老鐵們,小禮物走一波了,小汽車小火箭刷起來吧=========",time:"27",ismove:true,colorIndex:5},
{content:"老鐵們,小禮物走一波了,小汽車小火箭刷起來吧=========",time:"28",ismove:false,colorIndex:5},
{content:"老鐵們,小禮物走一波了,小汽車小火箭刷起來吧=========",time:"29",ismove:true,colorIndex:5},
{content:"老鐵們,小禮物走一波了,小汽車小火箭刷起來吧=========",time:"30",ismove:true,colorIndex:5},
{content:"馬上就下課了,瓦羅藍大陸走起了~~~",time:"31",ismove:true,colorIndex:5},
{content:"馬上就下課了,瓦羅藍大陸走起了~~~",time:"32",ismove:true,colorIndex:2},
{content:"馬上就下課了,瓦羅藍大陸走起了~~~",time:"33",ismove:true,colorIndex:2},
{content:"馬上就下課了,瓦羅藍大陸走起了~~~",time:"33",ismove:true,colorIndex:5},
{content:"馬上就下課了,瓦羅藍大陸走起了~~~",time:"34",ismove:true,colorIndex:5},
{content:"馬上就下課了,瓦羅藍大陸走起了~~~",time:"35",ismove:true,colorIndex:5},
{content:"馬上就下課了,瓦羅藍大陸走起了~~~",time:"36",ismove:true,colorIndex:2},
{content:"馬上就下課了,瓦羅藍大陸走起了~~~",time:"37",ismove:true,colorIndex:2}]
        //將測試數據備份
        copyArray(testArray , testArrayCopy)
        /*彈幕對象的構造函數,參數分別是:1.ismove:彈幕是否是移動的彈幕,2.spe:彈幕的移動速度,3.col:彈幕的顏色,4.text:彈幕的文本*/
        /*原型鏈方法 setTopValue設置縱坐標,setLeftValue設置橫坐標,moving完成坐標的改變,setId完成id值的設置*/
        function Caption( ismove , spe , col , text ) {
            this.isMove = ismove
            this.speed = spe
            this.color = col || "#ff0"
            this.content = text
            this.latestTime = 0 
            this.width = text.length * 20 
            this.id = 0
            this.topIndex = 0
            this.occupyPos = true 
            this.top = 300
            this.left = 0
            this.setLeftValue()
            this.setTopValue()
        }
        Caption.prototype.setTopValue = function  () {
            for(var i = 0 ,len = topObjs.length ; i < len ; i++){
                if (topObjs[i].blank) {
                    this.top = topObjs[i].value
                    this.topIndex = i
                    topObjs[i].blank = false 
                    break
                }
            }
        }
        Caption.prototype.setLeftValue = function  () {
            if (this.isMove) {
                this.left = cavWidth
            }
            else {
                var contentLength = this.content.length
                var nowItemLeft = 420 - contentLength * 9
                this.left = nowItemLeft
            }
        }
        Caption.prototype.moving = function () {
            if (this.isMove) {
                this.left-=this.speed
                if ( this.left + this.width < cavWidth && this.occupyPos) {
                    this.occupyPos = false 
                    topObjs[this.topIndex].blank = true 
                }
            } 
            else{
                this.latestTime += 1
                if (this.latestTime > 450) {
                    topObjs[this.topIndex].blank = true 
                }
            }
        }
        Caption.prototype.setId = function  () {
            this.id = capobjId
            capobjId++
        }

        var cap1 = new Caption(  false , 1 , 0 , "小禮物走一波,雙擊6666。。。。")
        capObjs.push(cap1)
        cap1.setId()
        
        //循環遍歷數組,根據對象的屬性繪制在畫布上
        function drawAllText () {
            ctx.clearRect( 0 , 0 , cavWidth , cavHeight)
            ctx.beginPath()
            for(var i=0 , len = capObjs . length ; i < len ; i++ ){
                ctx.fillStyle = capObjs[i].color
                ctx.font = "bold 20px Courier New"
                ctx.fillText( capObjs[i].content , capObjs[i].left , capObjs[i].top )
                ctx.closePath()
                capObjs[i].moving()
                // if (capObjs[i].left < - cavWidth ) {
                    // capObjs.splice (i ,1)
                    // if excute this statement , will has fault because some item in array is null
                    // solution is : write a new function to refresh the array   
                // }
            }
        }
        
        //更新數組,當對象已經超出范圍的時候從數組刪除這個對象
        function refreshObjs(objs) {
            for (var i = objs.length - 1; i >= 0; i--) {
                if (objs[i].left < - cavWidth || objs[i].latestTime > 450 ) {
                    objs.splice(i , 1)
                }

            }
        }
        
        //更新保存彈幕對象的數組
        function updateArray () {
            var now = parseInt( video.currentTime )
            for (var i = testArray.length - 1; i >= 0; i--) {
                var nowItemTime = parseInt(testArray[i].time) 
                if ( nowItemTime == now ) {
                    //首次寫的控制高度的方式,空間利用不充分,后來改為setTopValue中的方式
                    // var nowItemLeft = getLeftValue(testArray[i])
                    // var diffTime = Math.abs(nowItemTime - lastItemTime)
                    // if (diffTime < 6) { 
                    //     capHeight += 30
                    //     capHeight = capHeight > 400 ? 20 : capHeight
                    // }    
                    var temcolor = colors[testArray[i].colorIndex]
                    var temcap = new Caption (  testArray[i].ismove , 1 , temcolor , testArray[i].content  )
                    capObjs.push(temcap)
                    capObjs[capObjs.length - 1].setId()
                    temcap = null
                    testArray.splice(i,1)
                }
            }
        }
        
        //當用戶點擊send發送彈幕的回調函數
        function sendCaption (argument) {
            var inputEleTxt = inputEle.value
            var now = parseInt( video.currentTime )
            var inputIsmoveValue = ismoveInputEle.checked
            var temObj = {content:inputEleTxt,time:now,ismove:inputIsmoveValue,colorIndex:selectedColorIndex}
            testArray.push(temObj)
            inputEle.value = ""
        }

        // function getLeftValue (obj) {
        //     if (obj.ismove) {
        //         return 0
        //     }
        //     else {
        //         var contentLength = obj.content.length
        //         var nowItemLeft = 420 - contentLength * 9
        //         return nowItemLeft
        //     }
        // }
        
        //重新啟動canvas,用在人為導致進度條時間的改變
        function reinitCav (argument) {
            // testArray = testArrayCopy
            copyArray(testArrayCopy , testArray)
            capObjs = []
            capHeight = 0
            clearInterval(canvasTimer)
            canvasTimer = null
            initCanvas()
        }

        var canvasTimer = null 
        
        //初始化canvas,用在開始播放時
         function initCanvas () {
             if (canvasTimer == null ) {
                canvasTimer = setInterval(function (argument) {
                    drawAllText()
                    updateArray()
                    refreshObjs(capObjs)
                },10)
             }
            
        }//end function initCanvas
        
        //復制數組
        function copyArray (arr1 , arr2) {
            for (var i =0 , len=arr1.length ; i < len ; i++) {
                    arr2[i] = arr1[i]
                }    
        }

        //color select event 用戶發送彈幕的顏色控制代碼
        colorUl.addEventListener("click", function( e ){
            var prevSelectItemId = ""
            switch (selectedColorIndex) {
                case 0:
                    prevSelectItemId = "colorItemFrist"
                    break;
                case 1:
                    prevSelectItemId = "colorItemSecond"
                    break;
                case 2:
                    prevSelectItemId = "colorItemThrid"
                    break;
                case 3:
                    prevSelectItemId = "colorItemFourth"
                    break;
                case 4:
                    prevSelectItemId = "colorItemFifth" 
                    break;
                case 5:
                    prevSelectItemId = "colorItemSixth"
                    break;
                default:
                    // statements_def
                    break;
            }
            var prevSelectItem = document.getElementById(prevSelectItemId)
            prevSelectItem.className = ""
            var eventTarget = e.target
            eventTarget.className = "selectedColor"
            var eveTarId = eventTarget.id.substring(9)
            switch (eveTarId) {
                case "Frist":
                    selectedColorIndex = 0
                    break;
                case "Second":
                    selectedColorIndex = 1
                    break;
                case "Thrid":
                    selectedColorIndex = 2
                    break;
                case "Fourth":
                    selectedColorIndex = 3
                    break;
                case "Fifth":
                    selectedColorIndex = 4
                    break;
                case "Sixth":
                    selectedColorIndex = 5
                    break;
                default:
                    // statements_def
                    break;
            }
        }, false)

        video.addEventListener("playing" , function () {
            initCanvas()
        })
        
        //進度條改變執行代碼
        video.addEventListener("timeupdate", function  () {
            var nowPlayTime = video.currentTime
            var diffTime = Math.abs(nowPlayTime - prevPlayTime)
            prevPlayTime = nowPlayTime
            if (diffTime > 1) {
                reinitCav()
            }
        }, false)
        
        //視頻暫停執行代碼
        video.addEventListener("pause" , function () {
            clearInterval(canvasTimer)
            canvasTimer = null 
        })
        
        //點擊send的監聽事件
        sendEle.addEventListener("click" , sendCaption)
        
        //input的回車監聽事件
        inputEle.addEventListener("keydown", function(e) {
            var keynum = 0
            keynum = window.event ? e.keyCode : e.which
            if (keynum == 13) {
                sendCaption()
            }
        })


        var aaaa = function() {
            alert(1)
        }
        aaaa()
        // function b(aaaa){
        //     return aaaa()
        // }
        // b()    
    }//end
})()

希望能夠對想要制作彈幕的同學有所幫助,還可以去github下載完整的項目代碼:gitbub項目地址

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

【網站聲明】本站除付費源碼經過測試外,其他素材未做測試,不保證完整性,網站上部分源碼僅限學習交流,請勿用于商業用途。如損害你的權益請聯系客服QQ:2655101040 給予處理,謝謝支持。

相關文檔推薦

本篇文章主要介紹了html5中canvas圖表實現柱狀圖的示例,本文使用canvas來實現一個圖表,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本篇文章主要介紹了canvas 實現 github404動態效果的示例代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本篇文章主要介紹了教你使用Canvas處理圖片的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本篇文章主要介紹了Canvas與圖片壓縮的示例代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
這篇文章主要介紹了基于HTML5 Canvas的3D動態Chart圖表的示例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本篇文章主要介紹了canvas之自定義頭像功能實現代碼示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
主站蜘蛛池模板: 餐饮加盟网_特色餐饮加盟店_餐饮连锁店加盟 | 商秀—企业短视频代运营_抖音企业号托管 | 学考网学历中心| 诚暄电子公司首页-线路板打样,pcb线路板打样加工制作厂家 | 家用净水器代理批发加盟_净水机招商代理_全屋净水器定制品牌_【劳伦斯官网】 | 真空搅拌机-行星搅拌机-双行星动力混合机-广州市番禺区源创化工设备厂 | 无线遥控更衣吊篮_IC卡更衣吊篮_电动更衣吊篮配件_煤矿更衣吊篮-力得电子 | 东莞螺杆空压机_永磁变频空压机_节能空压机_空压机工厂批发_深圳螺杆空压机_广州螺杆空压机_东莞空压机_空压机批发_东莞空压机工厂批发_东莞市文颖设备科技有限公司 | 温州中研白癜风专科_温州治疗白癜风_温州治疗白癜风医院哪家好_温州哪里治疗白癜风 | 汽车整车综合环境舱_军标砂尘_盐雾试验室试验箱-无锡苏南试验设备有限公司 | 深圳法律咨询【24小时在线】深圳律师咨询免费 | 电动高压冲洗车_价格-江苏速利达机车有限公司 | 中山市派格家具有限公司【官网】 | 绿萝净除甲醛|深圳除甲醛公司|测甲醛怎么收费|培训机构|电影院|办公室|车内|室内除甲醛案例|原理|方法|价格立马咨询 | 金属管浮子流量计_金属转子流量计厂家-淮安润中仪表科技有限公司 | 开业庆典_舞龙舞狮_乔迁奠基仪式_开工仪式-神挚龙狮鼓乐文化传媒 | 依维柯自动挡房车,自行式国产改装房车,小型房车价格,中国十大房车品牌_南京拓锐斯特房车 - 南京拓锐斯特房车 | 成都思迪机电技术研究所-四川成都思迪编码器 | 河南mpp电力管_mpp电力管生产厂家_mpp电力电缆保护管价格 - 河南晨翀实业 | 铁艺,仿竹,竹节,护栏,围栏,篱笆,栅栏,栏杆,护栏网,网围栏,厂家 - 河北稳重金属丝网制品有限公司 山东太阳能路灯厂家-庭院灯生产厂家-济南晟启灯饰有限公司 | 鹤壁创新仪器公司-全自动量热仪,定硫仪,煤炭测硫仪,灰熔点测定仪,快速自动测氢仪,工业分析仪,煤质化验仪器 | 恒压供水控制柜|无负压|一体化泵站控制柜|PLC远程调试|MCGS触摸屏|自动控制方案-联致自控设备 | 电缆桥架生产厂家_槽式/梯式_热镀锌线槽_广东东莞雷正电气 | 金环宇|金环宇电线|金环宇电缆|金环宇电线电缆|深圳市金环宇电线电缆有限公司|金环宇电缆集团 | 强效碱性清洗剂-实验室中性清洗剂-食品级高纯氮气发生器-上海润榕科学器材有限公司 | 广州/东莞小字符喷码机-热转印打码机-喷码机厂家-广州瑞润科技 | 石油/泥浆/不锈钢防腐/砂泵/抽砂泵/砂砾泵/吸砂泵/压滤机泵 - 专业石油环保专用泵厂家 | 丹佛斯压力传感器,WISE温度传感器,WISE压力开关,丹佛斯温度开关-上海力笙工业设备有限公司 | 圣才学习网-考研考证学习平台,提供万种考研考证电子书、题库、视频课程等考试资料 | 展厅设计-展馆设计-专业企业展厅展馆设计公司-昆明华文创意 | 冰晶石|碱性嫩黄闪蒸干燥机-有机垃圾烘干设备-草酸钙盘式干燥机-常州市宝康干燥 | 智能交通网_智能交通系统_ITS_交通监控_卫星导航_智能交通行业 | 印刷人才网 印刷、包装、造纸,中国80%的印刷企业人才招聘选印刷人才网! | 济南轻型钢结构/济南铁艺护栏/济南铁艺大门-济南燕翔铁艺制品有限公司 | 环保袋,无纺布袋,无纺布打孔袋,保温袋,环保袋定制,环保袋厂家,环雅包装-十七年环保袋定制厂家 | 深圳APP开发_手机软件APP定制外包_小程序开发公司-来科信 | 考勤系统_人事考勤管理系统_本地部署BS考勤系统_考勤软件_天时考勤管理专家 | 北京康百特科技有限公司-分子蒸馏-短程分子蒸馏设备-实验室分子蒸馏设备 | 动力配电箱-不锈钢配电箱-高压开关柜-重庆宇轩机电设备有限公司 聚天冬氨酸,亚氨基二琥珀酸四钠,PASP,IDS - 远联化工 | 桁架机器人_桁架机械手_上下料机械手_数控车床机械手-苏州清智科技装备制造有限公司 | 体检车_移动CT车_CT检查车_CT车_深圳市艾克瑞电气有限公司移动CT体检车厂家-深圳市艾克瑞电气有限公司 |