欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

html5使用canvas实现弹幕功能示例

程序员文章站 2022-06-21 09:54:01
这篇文章主要介绍了html5使用canvas实现弹幕功能示例的相关资料,需要的朋友可以参考下... 17-09-11...

最近在着手开发弹幕视频网站,通过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项目地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。