首頁  >  文章  >  web前端  >  HTML如何利用canvas實現彈幕功能

HTML如何利用canvas實現彈幕功能

墨辰丷
墨辰丷原創
2018-06-04 15:00:471943瀏覽

本篇文章主要介紹HTML如何利用canvas實現彈幕功能,有興趣的朋友參考下,希望對大家有幫助。

簡介

 最近在做大作業的時候需要做一個彈幕播放器。借鑒了一下別人的源碼自己重新實現了一個,演示如下

#主要的功能有

發送彈幕
設定彈幕的顏色,速度和類型
顯示彈幕
 

已知缺陷:

#不能全螢幕

canvas沒有做自適應
沒有自訂播放器控制
沒有根據播放時間顯示對應的彈幕
彈幕不能實現懸停
已知的缺陷以後會再改進。網路上能找到的彈幕播放器的源碼一般只做了滾動的彈幕而沒有做靜止的彈幕,這裡我特意加上了靜止彈幕的實現。

Canvas繪製文字以及文字滾動效果

# 整個播放器的核心就是繪製文字以及做文字滾動的動畫,canvas中對於文字並沒有很好的動畫支持,只能透過自己實現,實現的思路就是不斷的清屏然後重寫文字,當清屏重寫的頻率達到24fps的時候就是流暢的動畫了。

先在HTML檔案中加入影片video標籤和畫布canvas標籤

#
<p id="barrageplayer">
    <canvas id="cv_video" width="900px" height="450px"></canvas>
    <video id="v_video" src="test.MP4" controls type="video/mp4"></video>
</p>

把canvas標籤的位置樣式設定為position:absolute然後影片和畫布就重疊在一起,看起來就是一個彈幕播放器了。然後為畫布添加彈幕相關的內容,首先取得畫布的相關資訊和設定畫布的字體大小和字體樣式

var c=document.getElementById("cv_video");
//获取画布大小
var c_height=c.height;
var c_width=c.width;
//获取画布
ctx=c.getContext("2d");
//设置字体样式
ctx.font="25px DengXian";
画布信息已经获取和设置,巧妇难为无米之炊,接着我们就要构造弹幕对象,使用的构造模式是动态原型模式
//弹幕对象
function Barrage(content,color,type,speed){
    this.content=content;
    this.color=color;
    this.type=type;
    this.speed=speed;
    if(this.type=="default"){
        this.height=parseInt(Math.random()*c_height)+10;
    }else if (this.type=="static top"){
        this.height=parseInt((c_height/2)-Math.random()*c_height/2)+10;
    }else if (this.type=="static bottom"){
        this.height=parseInt((c_height/2)+Math.random()*c_height/2)+10;
    }
    if(typeof this.move!="function"){
        Barrage.prototype.move=function(){
            if(this.type=="default"){
                this.left=this.left-this.speed;
            }
        }
    }
}

建構的彈幕物件初始化了各種參數,包括內容,顏色,運動類型和速度,定義了move()方法來控制彈幕的緩動,每出發一次move()方法向左滾動一個單位speed的像素。
彈幕物件建構完成之後就進入主題,動畫的製作,直接上代碼

//循环擦写画布实现动画效果
setInterval(function(){
    ctx.clearRect(0,0,c_width,c_height);
    ctx.save();
    for(var i=0;i<msgs.length;i++){
        if(msgs[i]!=null){
            if(msgs[i].type=="default"){
                handleDefault(msgs[i]);
            }else{
                handleStatic(msgs[i]);
           }
        }
    }
},20)

每20ms執行一次擦寫,ctx.clearRect (0,0,c_width,c_height);是將整張當前的畫布清除,然後使用ctx.save()將當前的畫布保存,接著遍歷彈幕列表(msgs是彈幕列表,當每發送一條彈幕都會將該彈幕實例加入清單),然後按照預設樣式的彈幕還是靜止樣式的彈幕分別處理。如果是預設樣式的彈幕將會按照以下的方法處理

//处理默认弹幕样式
function handleDefault(barrage){
    if(barrage.left==undefined||barrage.left==null){
        barrage.left=c.width;
    }else{
         if(barrage.left<-200){
            barrage=null;
        }else{
            barrage.move()
            ctx.fillStyle=barrage.color;
            ctx.fillText(barrage.content,barrage.left,barrage.height)
            ctx.restore();
        }
    }  
}

首先如果彈幕實例沒有設定left屬性則將畫布的寬度賦予它,如果彈幕實例已經退出畫布則將其置null以節省內存,否則的話就調用彈幕實例的move()方法改變left屬性的值,然後設置文字的顏色,一級寫入新的文字,恢復畫布。這樣就完成了一格動畫。

對於靜止彈幕的實作方法如下

//处理静止弹幕样式
function handleStatic(barrage){
    ctx.moveTo(c_width/2,barrage.height);
    ctx.textAlign="center";
    ctx.fillStyle=barrage.color;
    ctx.fillText(barrage.content,c_width/2,barrage.height);
    if(barrage.left==undefined||barrage.left==null){
        barrage.left=c.width;
    }else{
        if(barrage.left<-200){
            ctx.fillText("",c_width/2,barrage.height);                
            barrage=null;
            //ctx.restore();
            ctx.clearRect(0,0,c_width,c_height);        
        }else{
            barrage.left=barrage.left-6;
        }
    }
}

#首先將畫布的基點移到畫布的中心,需要注意的是這時候相對與生成了一張新的畫布,原來畫布的clearRect()方法已經不適用與這張畫布了。然後再設定文字對齊為居中對齊,設定文字樣式,填滿文字。因為彈幕是靜止的所以不需要進行緩動,但是靜止彈幕也是會消失的,需要設置一個標誌位來使他定時消失。這裡為了不佔用額外的屬性,我們直接使用left屬性作為標誌位,同樣進行left屬性的遞減,但不把遞減反映到畫布中,當left達到閾值,則使用ctx.clearRect()方法將彈幕清除。這樣就實現了靜止彈幕的處理。

其他關於顏色,樣式的設定有一定基礎的人應該是很容易掌握的在這裡就不多介紹了,自己看可運行程式碼部分理解一下就好。

總結

 這個專案主要是使用了canvas進行文字繪製以及實現文字的緩動動畫,主要用到的方法有

canvasDom.getContext()
canvas.save()/canvas.restore()
canvas.clearRect()
canvas.moveTo()

原來我對與save()和restore()是不能理解的,現在我算是有一點理解了,當你更改了畫布狀態,現在的畫布就已經不是原來的畫布,所以在修改畫布狀態之前先把畫布狀態保存,切換畫布狀態,完成工作之後,恢復為原來的畫布狀態繼續工作。像我處理靜態彈幕的時候,把畫布的基點改變了,那麼原來畫布的清除方法就不再適用於當前畫布,只有在當前畫布中自己使用另外的清除方法。然後再恢復到原來的畫布。

可運行程式碼

<!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>
</head>
<style type="text/css">
    .pickp{
        width: 30px;
        height: 30px;
        cursor: pointer;
        border: 2px solid gray;
        display: inline-block;
    }
    #white{
        background: white;
    }
    #red{
        background:#ff6666;
    }
    #yellow{
        background:#ffff00;
    }
    #blue{
        background:#333399;
    }
    #green{
        background:#339933;
    }
    #cv_video{
        position: absolute;
        z-index: 1;
    }
    #barrageplayer{
        position: relative;
        display: block;
        width: 900px;
        height: 500px;
    }
    #v_video{
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 0;
    }
</style>
<body>
    <p id="barrageplayer">
        <canvas id="cv_video" width="900px" height="450px"></canvas>
        <video id="v_video" src="test.MP4" controls type="video/mp4"></video>
    </p>
    <p id="barrageinput">
        <p>
            <input type="text" id="smsg" placeholder="请输入弹幕内容"/>
            <button id="send"> 发送</button>
        </p>
        <p id="colorpick">
            <p class="pickp" id="white"></p>
            <p class="pickp" id="red"></p>
            <p class="pickp" id="yellow"></p>
            <p class="pickp" id="blue"></p>
            <p class="pickp" id="green"></p>
        </p>
        <p id="typepick">
            <input type="radio" name="type" value="default">默认
            <input type="radio" name="type" value="static top">静止顶部 
            <input type="radio" name="type" value="static bottom">静止底部
        </p>
        <p id="speedpick">
            <input type="radio" name="speed" value="1">1X
            <input type="radio" name="speed" value="2">2X
            <input type="radio" name="speed" value="3">3X
        </p>
        <p id="stylepick"></p>
    </p>
    <script>
        var c=document.getElementById("cv_video");
        var typeDom=document.getElementsByName("type");
        var speedDom=document.getElementsByName("speed");
        var colorpick=document.getElementById("colorpick");
        var smsg=document.getElementById("smsg");
        var color="#white";
        var speed=1;
        var type="default";
        var msgs=[];
        //获取画布大小
        var c_height=c.height;
        var c_width=c.width;
        //获取画布
        ctx=c.getContext("2d");
        ctx.font="25px DengXian";
        //处理颜色选择
        colorpick.addEventListener(&#39;click&#39;,function(event){
            switch(event.target.id){
                case "white":
                    color="white";
                    break;
                case "red":
                    color="#ff6666";
                    break;
                case "yellow":
                    color="#ffff00";
                    break;
                case "green":
                    color="#339933";
                    break;
                case "blue":
                    color="#333399";
                    break;
            }
        })
        //处理发送弹幕
        document.getElementById("send").onclick=function(){
            var text=smsg.value;
            for(var i=0;i<typeDom.length;i++){
                if(typeDom[i].checked){
                    type=typeDom[i].value;
                    break;
                }
            }
            for(var i=0;i<speedDom.length;i++){
                if(speedDom[i].checked){
                    speed=2*parseInt(speedDom[i].value);
                    break;
                }
            }
            var tempBarrage=new Barrage(text,color,type,speed);
            msgs.push(tempBarrage);
        }
        //
        //弹幕功能部分代码
        //
        //弹幕对象
        function Barrage(content,color,type,speed){
            this.content=content;
            this.color=color;
            this.type=type;
            this.speed=speed;
            if(this.type=="default"){
                this.height=parseInt(Math.random()*c_height)+10;
            }else if (this.type=="static top"){
                this.height=parseInt((c_height/2)-Math.random()*c_height/2)+10;
            }else if (this.type=="static bottom"){
                this.height=parseInt((c_height/2)+Math.random()*c_height/2)+10;
            }
            if(typeof this.move!="function"){
                Barrage.prototype.move=function(){
                    if(this.type=="default"){
                        this.left=this.left-this.speed;
                    }
                }
            }
        }
        //循环擦写画布实现动画效果
        setInterval(function(){
            ctx.clearRect(0,0,c_width,c_height);
            ctx.save();
            for(var i=0;i<msgs.length;i++){
                if(msgs[i]!=null){
                    if(msgs[i].type=="default"){
                        handleDefault(msgs[i]);
                    }else{
                        handleStatic(msgs[i]);
                    }
                }
            }
        },20)
    //处理默认弹幕样式
    function handleDefault(barrage){
        if(barrage.left==undefined||barrage.left==null){
            barrage.left=c.width;
        }else{
            if(barrage.left<-200){
                barrage=null;
            }else{
                barrage.move()
                ctx.fillStyle=barrage.color;
                ctx.fillText(barrage.content,barrage.left,barrage.height)
                ctx.restore();
            }
        }  
    }
    //处理静止弹幕样式
    function handleStatic(barrage){
        ctx.moveTo(c_width/2,barrage.height);
        ctx.textAlign="center";
        ctx.fillStyle=barrage.color;
        ctx.fillText(barrage.content,c_width/2,barrage.height);
        if(barrage.left==undefined||barrage.left==null){
            barrage.left=c.width;
        }else{
            if(barrage.left<-200){
                ctx.fillText("",c_width/2,barrage.height);                
                barrage=null;
                //ctx.restore();
                ctx.clearRect(0,0,c_width,c_height);        
            }else{
                barrage.left=barrage.left-6;
            }
        }
    }
    </script>
</body>
</html>

總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。

相關推薦:

H5 Canvas使用案例詳解

怎麼使用Vue canvas實作行動觸控板功能

js canvas實作滑動拼圖驗證碼功能

#

以上是HTML如何利用canvas實現彈幕功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn