Canvas彈幕實現

canvas原生實現直播視頻彈幕效果。javascript

上一篇中用動態建立DOM元素實現彈幕效果,好處是能夠在DOM元素上添加事件,但問題是當大量彈幕出現會形成頁面卡頓,因而嘗試用canvas繪製彈幕效果。css

原文連接

canvas知識

繪製文字

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.font = '20px Microsoft YaHei';          //字體、大小
ctx.fillStyle = '#000000';                  //字體顏色
ctx.fillText('canvas 繪製文字', 100, 100);   //文本,字體x,y座標

文本寬度

ctx.measureText('文本寬度').width

清除繪製內容

ctx.clearRect(0, 0, width, height);

實現步驟

一、建立canvas元素利用絕對定位覆蓋在視頻上
二、建立Barrage類,添加的彈幕緩存到彈幕列表中,並記錄相應彈幕信息
三、繪製彈幕文本,用文本偏移量控制移動速度
四、計算當文本超出畫布時移出彈幕列表html

代碼

//html
<div style="position:relative;width:500px;height:400px;text-align:center;">
    <video controls="controls" autoplay="autoplay" style="width:100%;height:100%;">
        <source src="http://www.w3school.com.cn/i/movie.ogg" type="video/ogg" />
        <source src="http://www.w3school.com.cn/i/movie.mp4" type="video/mp4" /> 
        Your browser does not support the video tag.
    </video>

    <canvas id="canvas" width="500" height="400" style="position:absolute;top:0;left:0;">
        您的瀏覽器不支持canvas標籤。
    </canvas>
</div>

//js
(function () {

    class Barrage {
        constructor(canvas) {
            this.canvas = document.getElementById(canvas);
            let rect = this.canvas.getBoundingClientRect();
            this.w = rect.right - rect.left;
            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));
        }

        //繪製文字
        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;
        }

    }

    let barrage = new Barrage('canvas');
    barrage.draw();

    const textList = ['彈幕', '666', '233333333', 
        'javascript', 'html', 'css', '前端框架', 'Vue', 'React',
        'Angular','測試彈幕效果'
    ];

    textList.forEach((t) => {
        barrage.shoot(t);
    })

})();

效果

效果

總結

canvas能夠實現不少動畫效果,尤爲是當咱們須要動態建立大量元素時,使用canvas能夠優化動畫顯示效果,改善用戶體驗,提高性能。前端

相關文章
相關標籤/搜索