歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> HTML5-Canvas實例:2D折線數據圖與2D扇形圖

HTML5-Canvas實例:2D折線數據圖與2D扇形圖

日期:2017/3/1 9:33:08   编辑:Linux編程
基礎知識:
<canvas id="demo" width="400" height="400"></canvas>

在頁面上創建canvas標簽,然後獲取canvas這個元素,因為是畫2D圖,所以是調用.getContext('2d') 二維圖方法

var target = document.getElementById('demo'),
     pic = target.getContext('2d');

canvas作圖的平面空間,該空間的每個點都有自己的坐標,x表示橫坐標,y表示豎坐標。原點(0, 0)位於圖像左上角,x軸的正向是原點向右,y軸的正向是原點向下。

部分API的介紹: 

  pic.beginPath(); //創建開始描繪路徑(每一條線都需要重新創建一次,否則以後的操作【如填充顏色】都會反映在此路徑)
    pic.moveTo(0, 0); //描繪的起點
    pic.lineTo(100,100); // 設置描繪線的終點,可以調用多次(以上次的終點為起點,繼續描繪)
    pic.lineTo(240,340);
    pic.lineWidth = 1; //設置寬度
    pic.strokeStyle = '#259'; //設置顏色
    pic.stroke(); //填充
    pic.closePath(); //關閉此路徑,可選

封裝:

  描繪路徑必需知道起點坐標與終點坐標,因為可能是多次描繪,所以就需要用到二維數組把各個坐標保存下來,如[ [0,0],[100,50],[2,50] ],然後遍歷二維數組,多次調用lineTo方法進行描繪。封裝函數如下:

// 畫線 
    function drawContLine(opt){
        pic.beginPath();
        var path = opt.path,//[[0,0],[20,30]......]
            color = opt.color;
        pic.moveTo(path[0][0],path[0][1]);
        var n = 1,
            len = path.length;
        for(;n<len;n++){
            pic.lineTo(path[n][0],path[n][1]);
        }
        pic.lineWidth = 1;
        pic.strokeStyle = color;
        pic.stroke();
        pic.closePath();
    }

例子:月份成績分數對比曲線圖

  

完整代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"/>
    <title>Document</title>
    <style type="text/css">
    .ui-fill{border:1px solid #666;border-top:none;border-right:none;width:400px;height:400px;margin:50px auto;position:relative;}
    .scroe span{position:absolute;left:-40px;}
    .a10{top:-10px;}.a9{top:30px;}.a8{top:70px;}.a7{top:110px;}.a6{top:150px;}
    .a5{top:190px;}.a4{top:230px;}.a3{top:270px;}.a2{top:310px;}.a1{top:350px;}
    .year span{position:absolute;top:410px;white-space:nowrap;color:#700404;}
    .y1{left:70px;}.y2{left:150px;}.y3{left:230px;}.y4{left:310px;}.y5{left:390px;}
    </style>
</head>
<body>
    <div class="ui-fill">
        <canvas id="demo" width="400" height="400"></canvas>
        <div class="scroe">
            <span class="a1">10</span>
            <span class="a2">20</span>
            <span class="a3">30</span>
            <span class="a4">40</span>
            <span class="a5">50</span>
            <span class="a6">60</span>
            <span class="a7">70</span>
            <span class="a8">80</span>
            <span class="a9">90</span>
            <span class="a10">100</span>
        </div>
        <div class="year">
            <span class="y1">1月</span>
            <span class="y2">2月</span>
            <span class="y3">3月</span>
            <span class="y4">4月</span>
            <span class="y5">5月</span>
        </div>
    </div>
    <script type="text/javascript">
    var target = document.getElementById('demo');
    var pic = target.getContext('2d');
    //參數
    var sum = 400,
        ratio = 400/100;
    // 畫線 
    function drawContLine(opt){
        pic.beginPath();
        var path = opt.path,//[[0,0],[20,30]......]
            color = opt.color;
        pic.moveTo(path[0][0],path[0][1]);
        var n = 1,
            len = path.length;
        for(;n<len;n++){
            pic.lineTo(path[n][0],path[n][1]);
        }
        pic.lineWidth = 1;
        pic.strokeStyle = color;
        pic.stroke();
        pic.closePath();
    }
    // 刻度線
    (function(){
        var scale = 20,
            i = sum/scale,
            n = 0;
        for(;n<i;n++){
            drawContLine({'path':[[scale*n*4,0],[scale*n*4,sum]],'color':'#f4f4f4'});
            drawContLine({'path':[[0,scale*n],[sum,scale*n]],'color':'#f4f4f4'});                        
        }
    })();
    // 分數轉化為坐標輸出
    function transforCoor(opt){
        var scroes = opt.scroes,
            scale = 20*4,
            n = 0,
            len = scroes.length,
            a_path = [];
        for(;n<len;n++){
            var x = sum - scroes[n]*ratio;
            var arry = [scale*(n+1),x];
            //console.log(arry);
            a_path.push(arry);
        }

        drawContLine({'path':a_path,'color':opt.color});
    }
    transforCoor({'scroes':[90,80,98,70,60],'color':'#259'});
    transforCoor({'scroes':[88,86,85,84,85],'color':'#f60'});
    </script>
</body>
</html>

扇形圖:

ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);

  arc方法的x和y參數是圓心坐標,radius是半徑,startAngle和endAngle則是扇形的起始角度和終止角度(以弧度表示,Math.PI*2表示360度),anticlockwise表示做圖時應該逆時針畫(true)還是順時針畫(false)

  例子:

  <canvas id="j_canvas" width="300" height="300"></canvas>
    <script type="text/javascript">
    /*
    * @param {obj}
    * @param {string} id canvas的id
    * @param {array} colors 顏色
    * @param {array} pers 占的比值(小數格式)
    */
    function drawSector(opt){
        var target = document.getElementById(opt.id),
            ctx = target.getContext('2d'),
            colors = opt.colors,
            pers = opt.pers,
            n = 0,
            len = colors.length,
            w = target.getAttribute('width'),
            v = 0,
            s = 0,
            e  = 0;
        for(;n<len;n++){
            ctx.beginPath(); 
                v = n==0?0:Number(pers[n-1]),
                s = s + v,
                e =  e + Number(pers[n]);
            ctx.arc(w/2, w/2, w/2, Math.PI*2*s, Math.PI*2*e,false); 
            //畫出結束半徑
            ctx.lineTo(w/2,w/2);
            ctx.fillStyle = colors[n]; 
            ctx.fill();
        }
    }
    drawSector({'id':'j_canvas','colors':['#259','#333','#f60','#999'],'pers':['0.2','0.4','0.3','0.1']});
</script>

--------------------------------------分割線 --------------------------------------

HTML5 地理位置定位(HTML5 Geolocation)原理及應用 http://www.linuxidc.com/Linux/2012-07/65129.htm

HTML5移動開發即學即用(雙色) PDF+源碼 http://www.linuxidc.com/Linux/2013-09/90351.htm

HTML5入門學習筆記 http://www.linuxidc.com/Linux/2013-09/90089.htm

HTML5移動Web開發筆記 http://www.linuxidc.com/Linux/2013-09/90088.htm

HTML5 開發中的本地存儲的安全風險 http://www.linuxidc.com/Linux/2013-06/86486.htm

《HTML5與CSS3權威指南》及相配套源碼 http://www.linuxidc.com/Linux/2013-02/79950.htm

關於 HTML5 令人激動的 10 項預測 http://www.linuxidc.com/Linux/2013-02/79917.htm

HTML5與CSS3實戰指南 PDF http://www.linuxidc.com/Linux/2013-02/79910.htm

--------------------------------------分割線 --------------------------------------

Copyright © Linux教程網 All Rights Reserved