HTML5 彈幕

網上無心中看到一段優秀的彈幕代碼,作了一個H5彈幕
預覽地址:戳這裏css

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
    <title>彈幕</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>

</head>
<body>

  <div id='con' ></div>

  <script>
    
      
var mybarrage = (function($) {
   return {
    create: function(config){
        var style = '';
        style += config.area.left ? ('left:'+ config.area.left+'px;'):'';
        //style += config.area.right ? ('right:'+ config.area.right+'px;'):'';
        //style += config.area.top ? ('top:'+ config.area.top+';'):'';
        //style += 'bottom:'+ config.area.bottomNum +'%;';
    
        $("#con").append('<div id="barrage-wrapper" style="position:relative;z-index:100;'+ style +'"></div>');

        //new一個彈幕管理器
        var manage = new mybarrage.init.BarrageManager();

        manage.load();
    },
    init: function(){
        var json = [
          { id: 2, fromUserName: '李尋歡', content: "梨花劍", fromUserIcon: "https://www.baidu.com/favicon.ico" },
          { id: 3, fromUserName: '黃藥師', content: "輕功", fromUserIcon: "https://www.baidu.com/favicon.ico" },
          { id: 4, fromUserName: '周杰倫', content: "唱歌", fromUserIcon: "https://www.baidu.com/favicon.ico" },
           { id: 5, fromUserName: '洪金寶', content: "功夫", fromUserIcon: "https://www.baidu.com/favicon.ico" }
        ]
        //彈幕管理器
        function BarrageManager (options) {
            this.opts = {
                url       : [],
                loadDelay : 5000 ,  // 輪詢時間間隔
            }

            $.extend( this.opts , options);
            //new一個彈幕隊列集合
            this.bc = new BarrageCollection();
        }

        //彈幕管理器加載數據
        BarrageManager.prototype.load = function (data) {
            var self = this ;

            if(data == null){
              data = self.opts.url;
            }
            
            for(var i = 0 ; i < data.length ; i++) {
              
                //全部初始數據轉化成彈幕對象,放進彈幕隊列集合中
                self.bc.add(new Barrage({
                    id:data[i].id,
                    name:data[i].fromUserName,
                    text:data[i].content,
                    icon:data[i].fromUserIcon
                }));
            }
            //彈幕管理器開始工做
            self.loop();
        }

        // 彈幕管理器工做
        BarrageManager.prototype.loop = function () {
            var len = this.bc.mq.length , self = this  ;
            while (len--) {
                // 彈幕隊列集合
                this.bc.mq[len].start(this.bc , len);
            }   

            // setTimeout(function () {
            //     self.load();
            // } , this.opts.loadDelay);
        }

        function BarrageCollection () {
            this.mq = [] ;
        }

        BarrageCollection.prototype.add = function (barrage) {
            this.mq.push(barrage);
        }

        //彈幕隊列集合刪除彈幕
        BarrageCollection.prototype.remove = function (barrage) {
            var index = this.mq.findIndex(function (item) {
                return barrage.opts.id == item.opts.id ;
            });
            if(index != -1) {
                this.mq.splice(index , 1);
            }
            barrage.opts.$el.remove();
        }

        function Barrage (options) {
            this.opts = {
                $el         : null ,
                left        : 0 ,
                bgColor     : [Math.floor(Math.random()*255),Math.floor(Math.random()*255),Math.floor(Math.random()*255)] ,
                offset      : 1000 ,      // 使彈幕徹底移出屏幕外
                duration    : 10000 ,   // 彈幕從右往左移動的時間 
                delayTime   : 1000 ,    // 彈幕延遲移動時間
            };
            $.extend( this.opts , options);
            this.init();
        }

        Barrage.prototype.init = function () {

            //this.opts.$el = $("<span class='barrageItem'><img src="+this.opts.icon+"><em>"+this.opts.name+":</em>"+this.opts.text+"</span>");
            this.opts.$el = $("<span class='barrageItem'>"+this.opts.text+"</span>");
            var top = Math.ceil(Math.random() * 10 );
            this.opts.$el.css({
                top:top * 40 +'px',
                //backgroundColor:"rgb("+this.opts.bgColor.join(",")+")",
                    color:"rgb("+this.opts.bgColor.join(",")+")",
                //right:0,
                position:'absolute'
            });

            var delay = Math.ceil(Math.random()*10);
            this.opts.delayTime *= Math.abs(delay - 5);

            //var dur = Math.ceil(Math.random() * 10);
            // this.opts.duration += dur * 1000 ; 


            $('#barrage-wrapper').append(this.opts.$el);
            this.opts.left = -this.opts.$el.width() - this.opts.offset ;
            
        }

            //彈幕開始移動
        Barrage.prototype.start = function (bc , index) {
            var self = this ;
            
        
            setTimeout(function () {
                self.move(bc);
            }, this.opts.delayTime);
        }

        //彈幕移動
        Barrage.prototype.move = function (bc) {
            var self = this ;
          // 彈幕隊列集合刪除這個彈幕
            this.opts.$el.animate({left:'-150%'},this.opts.duration ,"linear", function () { bc.remove(self);});

        }

        return {
            BarrageManager: BarrageManager,
            BarrageCollection: BarrageCollection,
            Barrage: Barrage
        }
    }()
   }
})($)
    
    var width = document.documentElement.offsetWidth || document.documentElement.offsetWidth||window.innerWidth
    var BarrageManager = mybarrage.init.BarrageManager;
    var Barrage = mybarrage.init.Barrage;
        
  function submit(){
    let text = $('#custmerEnter').val();
    let manage = new BarrageManager();

        manage.load();

        manage.bc.add(new Barrage({
            id: +new Date(),
            name: '張三風',
            text: text,
            icon: 'https://pic4.zhimg.com/da8e974dc_xs.jpg'
        }));
        manage.loop();
  
  }
  mybarrage.create({
        area:{
            left: width,
            //right: -10,
            top: '5%'
        }
    }) 
    
    

  </script>

  <input type='text' id='custmerEnter' />
  <button onclick='submit()'>提交</button>
</body>
</html>
相關文章
相關標籤/搜索