canvas で対比横棒グラフを作る

  • 1
    いいね
  • 0
    コメント

canvas_jun0201.png

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<script src="/js/jquery-3.2.1.min.js"></script>
<script src="bar.js"></script>
<title>canvas描く対比横棒グラフ</title>
</head>
<body>
<div>
<canvas id="bar_area" width="800" height="400"></canvas>
</div>
<hr />
Jun/02/2017<p />
</body>
</html>
bar.js
// -------------------------------------------------------------------------
//  bar.js
//
//                      Jun/02/2017
// -------------------------------------------------------------------------
jQuery  (function ()
{
    const file_json = "pacific.json"

    jQuery.getJSON (file_json,function (data)
        {
        bar_proc (data)
        })
})

// -------------------------------------------------------------------------
function bar_proc (data)
{
    var bar = document.getElementById('bar_area')
    var ctx = bar.getContext('2d')

    ctx.font = "18px 'MS Pゴシック'"
    ctx.strokeStyle = "black" 

    var yy = 30
    ctx.strokeText("パシフィック",250,yy)
    ctx.strokeText("勝利",420,yy)
    ctx.strokeText("敗北",150,yy)


    var xx = 250
    yy = 70
    ctx.strokeStyle = "blue" 
    for (it in data)
        {
        const unit = data[it]
        ctx.strokeText(unit.team,xx,yy)
        draw_win_proc (ctx,xx+120,yy-18,unit.win)
        draw_lose_proc (ctx,xx-30,yy-18,unit.lose)
        yy += 50
        }
}

// -------------------------------------------------------------------------
function  draw_win_proc (ctx,xx,yy,nn)
{
ctx.beginPath();
ctx.fillStyle = 'green'
    ctx.rect (xx,yy,nn*5,20)
    ctx.fill()
    ctx.closePath()
ctx.stroke();

}

// -------------------------------------------------------------------------
function  draw_lose_proc (ctx,xx,yy,nn)
{
ctx.beginPath();
ctx.fillStyle = 'red'
    ctx.rect (xx-nn*5,yy,nn*5,20)
    ctx.fill()
    ctx.closePath()
ctx.stroke();

}

// -------------------------------------------------------------------------
pacific.json
[
{"team": "楽天","win": 33,"lose": 12},
{"team": "ソフトバンク","win": 32,"lose": 20},
{"team": "西武","win": 26,"lose": 21},
{"team": "オリックス","win": 22,"lose": 27},
{"team": "日本ハム","win": 21,"lose": 28},
{"team": "ロッテ","win": 15,"lose": 35}
]