3种方法实现弹幕效果

本文实现弹幕效果的三种方法:1、Canvas实现 2、Jquery实现 3、js原生实现

1、Canvas弹幕实现

借鉴于:https://segmentfault.com/a/1190000011723466
效果图:

在这里插入图片描述

代码如下:
//index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>The Canavas Danmu Wall</title>
    <link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
    <div class="container">
        <canvas id="drawing" width="1000" height="500"></canvas>
        <div style="text-align:center; vertical-align:middle; margin-top:10px;">
        <input  id="text" value=""   placeholder="说点什么?" />
        </div>

        <div style="margin-top:10px">
        <button id="btn1">发射</button>  
        <button id="btn2">清空</button>
       </div>

    </div>

    <script type="text/javascript" src="main.js"></script>
</body>
</html>
//css.style文件
#drawing{
    border:2px solid #44b8c0;
    margin-top:10px;
}

#text{
    width:450px; 
    height:30px; 
    border:1px solid #44b8c0;
    font-size:20px;
}

.container{
    margin: 0 auto;
    width:1000px;
}

#btn1{
    border:1px solid  #44b8c0;
    border-radius:5px;

    background: url("1.jpg") no-repeat;
    margin-left:450px;
    height:30px;
    width:60px;
}

#btn2{
    border:1px solid  #44b8c0;
    border-radius:5px;

    background: url("1.jpg") no-repeat;
    margin-left:20px;
    height:30px;
    width:60px;
}
// main.js文件
(function () {

    class Barrage {
        constructor() {
            this.canvas = document.getElementById('drawing');
            let rect = this.canvas.getBoundingClientRect();
            this.w = rect.right - rect.left;//left为元素左边到视窗的距离 right为元素右边到视窗的距离
            this.h = rect.bottom - rect.top;
            this.ctx = this.canvas.getContext('2d');
            this.ctx.font = '20px Microsoft YaHei';
            this.barrageList = [];
        }
    
        //添加弹幕列表
        shoot(value) {
            let top = this.getTop();
            let color = this.getColor();
            let offset = this.getOffset();
            let width = Math.ceil(this.ctx.measureText(value).width);//如果您需要在文本向画布输出之前,就了解文本的宽度,那么请使用该方法。
           
            let barrage = {
                value: value,
                top: top,
                left: this.w,
                color: color,
                offset: offset,
                width: width
            }
            this.barrageList.push(barrage);
        }
    
        //开始绘制
        draw() {
            if (this.barrageList.length) {
                this.ctx.clearRect(0, 0, this.w, this.h);
                for (let i = 0; i < this.barrageList.length; i++) {
                    let b = this.barrageList[i];
                    if (b.left + b.width <= 0) {
                        this.barrageList.splice(i, 1);
                        i--;
                        continue;
                    }
                    b.left -= b.offset;
                    this.drawText(b);
                }
            }
            requestAnimationFrame(this.draw.bind(this));//JS动画
        }
    
        //绘制文字
        drawText(barrage) {
            this.ctx.fillStyle = barrage.color;
            this.ctx.fillText(barrage.value, barrage.left, barrage.top);
        }
    
        //获取随机颜色
        getColor() {
            return '#' + Math.floor(Math.random() * 0xffffff).toString(16);
        }
    
        //获取随机top
        getTop() {
            //canvas绘制文字x,y坐标是按文字左下角计算,预留30px
            return Math.floor(Math.random() * (this.h - 30)) + 30;
        }
    
        //获取偏移量
        getOffset() {
            return +(Math.random() * 4).toFixed(1) + 1;
        }
        //清空弹幕
        clearDanmu(){
            this.barrageList = [];
            this.ctx.clearRect(0, 0, this.w, this.h);
        }
    
    }
    
    let barrage = new Barrage();
    barrage.draw();
    
      var btn1= document.getElementById('btn1');
      btn1.addEventListener("click",function(){
        var input=document.getElementById("text");
        var value1 =input.value;
        input.value='';
        barrage.shoot(value1);

        input.focus();
      },false);

       var btn2 =document.getElementById('btn2');
       btn2.addEventListener("click",function(){
        barrage.clearDanmu();
      },false);  

     
    
    
    })();

2、Jquery弹幕实现

借鉴于:https://segmentfault.com/a/1190000009948824
效果图:在这里插入图片描述
代码如下:
//index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>The Jquery Danmu Wall</title>
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="screen_container"></div>
    <div class="screen_toolbar">
        <input id="screenBullText" type="text" placeholder="请输入弹幕内容"/>
        <button class="send">发射</button>
        <button class="clear">清空</button>
    </div>
</body>

<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script src="main.js"></script>
</html>
//style.css文件
.screen_container{
    position: relative;
    width: 600px;
    height: 400px;
    margin:30px auto;
    background: #000;
    overflow: hidden;

}

.screen_toolbar{
    width: 600px;
    margin:20px auto;
    text-align: center;
}
//main.js文件
// 弹幕定时器
var timers = [];
// 控制弹幕显隐变量
var isShow = true;
// 监听发送按钮
$(".send").on("click", function () {
    // 创建弹幕
   
    var jqueryDom = createScreenbullet($("#screenBullText").val());
    $("#screenBullText").val("");
    $("#screenBullText").focus();
    // 添加定时任务
    addInterval(jqueryDom);
});
// 监听关闭弹幕按钮
$(".clear").on("click", function () {
    if (isShow) {
        $(".bullet").css("opacity", 0);
        isShow = false;
    } else {
        $(".bullet").css("opacity", 1);
        isShow = true;
    }   
});
// 新建一个弹幕
function createScreenbullet(text) {
    var jqueryDom = $("<div class='bullet'>" + text + "</div>");
    var fontColor = "rgb(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random()) + ")";
    var fontSize = Math.floor((Math.random() + 1) * 24) + "px";
    var left = $(".screen_container").width() + "px";
    var top = Math.floor(Math.random() * 400) + "px";
    top = parseInt(top) > 352 ? "352px" : top;
    jqueryDom.css({
        "position": 'absolute',
        "color": fontColor,
        "font-size": fontSize,
        "left": left,
        "top": top
    });
    $(".screen_container").append(jqueryDom);
    return jqueryDom;
}
// 为弹幕添加定时任务
function addInterval(jqueryDom) {
    var left = jqueryDom.offset().left - $(".screen_container").offset().left;
    var timer = setInterval(function () {
        left--;
        jqueryDom.css("left", left + "px");
        if (jqueryDom.offset().left + jqueryDom.width() < $(".screen_container").offset().left) {
            jqueryDom.remove();
            clearInterval(timer);
        }
    }, 10);
    timers.push(timer);
}

3、原生JS弹幕实现

借鉴于:https://segmentfault.com/a/1190000011686448
效果图:在这里插入图片描述
代码如下:
//index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />    
</head>
<body>
    <div class="container">
        <div id="content" class="content"></div>
        <div class="content-opt">
            <div id="content-text" class="content-text"></div>
            <div class="content-input">
                <input id="text" type="text">
                <button id="send">发送</button>
            </div>
        </div>
    </div>
</body>
<script src="main.js"></script>
</html>
//style.css文件
* {
    box-sizing: border-box;
    outline: none;
}

p {
    margin: .5em;
    word-break: break-all;
}

.container {
    position: relative;
    width: 700px;
    height: 500px;
    margin: auto;
    padding-right: 200px;
}

.content {
    width: 100%;
    height: 100%;
    border: 1px solid #ccc;
}

.content-opt {
    position: absolute;
    top: 0;
    right: 0;
    width: 200px;
    height: 100%;
}

.content-text {
    height: calc(100% - 30px);
    margin-bottom: 30px;
    border: 1px solid #ccc;
    overflow: auto;
}

.content-input {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 30px;
    border: 1px solid #ccc;
}

.content-input input {
    width: 70%;
    padding: 2px;
    border-radius: 5px;
}

.content-input button {
    padding: 3px 10px;
    border: none;
    border-radius: 5px;
    background: rgb(90, 154, 214);
}

//main.js文件
(function () {
    class Barrage {
        constructor(id) {
            this.domList = [];
            this.dom = document.querySelector('#' + id);
            if (this.dom.style.position == '' || this.dom.style.position == 'static') {
                this.dom.style.position = 'relative';
            }
            this.dom.style.overflow = 'hidden';
            let rect = this.dom.getBoundingClientRect();
            this.domWidth = rect.right - rect.left;
            this.domHeight = rect.bottom - rect.top;
        }

        shoot(text) {
            let div = document.createElement('div');
            div.style.position = 'absolute';
            div.style.left = this.domWidth + 'px';
            div.style.top = (this.domHeight - 20) * +Math.random().toFixed(2) + 'px';
            div.style.whiteSpace = 'nowrap';
            div.style.color = '#' + Math.floor(Math.random() * 256).toString(10);
            div.innerText = text;
            this.dom.appendChild(div);

            let roll = (timer) => {
                let now = +new Date();
                roll.last = roll.last || now;
                roll.timer = roll.timer || timer;
                let left = div.offsetLeft;
                let rect = div.getBoundingClientRect();
                if (left < (rect.left - rect.right)) {
                    this.dom.removeChild(div);
                } else {
                    if (now - roll.last >= roll.timer) {
                        roll.last = now;
                        left -= 3;
                        div.style.left = left + 'px';
                    }
                    requestAnimationFrame(roll);
                }
            }
            roll(50 * +Math.random().toFixed(2));
        }

    }

    let barage = new Barrage('content');

    function appendList(text) {
        let p = document.createElement('p');
        p.innerText = text;
        document.querySelector('#content-text').appendChild(p);
    }

    document.querySelector('#send').onclick = () => {
        let text = document.querySelector('#text').value;
        barage.shoot(text);

        appendList(text);
    };

    const textList = ['弹幕', '666', '233333333', 'javascript', 'html', 'css', '前端框架', 'Vue', 'React', 'Angular',
        '测试弹幕效果'
    ];
    textList.forEach((s) => {
        barage.shoot(s);
        appendList(s);
    })
})();
  • 5
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值