利用 Canvas 實作統計圖表

Canvas 支援2D圖形描繪,因此只要整理好相關的數據,就能透過相關的 API 將其轉換成為視覺化的圖形。

原文:http://www.kangting.tw/2014/03/canvas.html

Canvas 支援2D圖形描繪,因此只要整理好相關的數據,就能透過相關的 API 將其轉換成為視覺化的圖形。考慮以下的資料:

月份 January February March April May June July
銷售額 25 32 40 61 36 25 40

建立一組對應此資料的資料物件:

var chartdata = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    data: [25, 32, 40, 61, 36, 25, 40],
    color: ["red", "orange", "yellow", "green", "blue", "black", "gray"]
}

接下來透過 Canvas API ,於底下配置 Canvas 元素中,逐一描繪對應的圖表。 以下為需要的程式碼:

<script>
 //JSON 物件
        var start_x = 60;
        var start_y = 400;
 
        var chartdata = {
            labels: ["January", "February", "March",
"April", "May", "June", "July"],
            data: [25, 32, 40, 61, 36, 25, 40],
            color: ["red", "orange", "yellow",
"green", "blue", "black", "ghostwhite"]
        }
        var cvs = document.getElementById('cvs');
        var ctx = cvs.getContext('2d');
       
        // Y
        ctx.beginPath();
        ctx.moveTo(start_x, 100);
        ctx.lineTo(start_x, start_y);
        ctx.stroke();
        // X
        ctx.beginPath();
        ctx.moveTo(start_x, start_y);
        ctx.lineTo(520, start_y);
        ctx.stroke();
 
        ctx.lineWidth = 20;
        for (i = 0; i < 7; i++) {
            ctx.beginPath();
            ctx.strokeStyle = chartdata.color[i] ;
            ctx.moveTo((i + 1) * start_x + start_x, start_y);
            ctx.lineTo((i + 1) * start_x + start_x, start_y –
chartdata.data[i] * 5);
            ctx.stroke();
 
            ctx.fillText(chartdata.labels[i], (i + 1) *
start_x + start_x, start_y + 38);
        }
</script>