index.html
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="bar.js"></script>
<title>canvas描く対比横棒グラフ</title>
</head>
<body>
<div>
<canvas id="bar_area" width="800" height="400"></canvas>
</div>
<hr />
Aug/07/2023<p />
</body>
</html>
bar.js
// -------------------------------------------------------------------------
//	bar.js
//
//						Aug/07/2023
// -------------------------------------------------------------------------
window.onload = ()=>
{
	const file_json = "pacific.json"
	fetch(file_json).then((response) => {
		if(!response.ok) {
			console.log('Read error!')
			throw new Error('error')
		} 
		console.log('Read ok!')
		return response.text()
	}).then((data)  => {
		const data_aa = JSON.parse(data)
		bar_proc (data_aa)
		})
}
// -------------------------------------------------------------------------
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}
]
