CSS と SVG のみを使用して円グラフを描く方法について説明します。
<div class="pie-chart-box"> <svg class="pie-chart" width="150" height="150"> <circle class="chart-1" cx="50%" cy="50%" r="40"></circle> <circle class="chart-2" cx="50%" cy="50%" r="40"></circle> </svg> <div class="text">75%</div> </div>
.pie-chart-box { position: relative; width: 150px; height: 150px; .pie-chart { border: 1px solid #ddd; transform: rotate(-90deg); .chart-1 { stroke: #ddd; stroke-width: 4; fill: none; } .chart-2 { stroke: #339; stroke-width: 8; stroke-dasharray: calc(40 * 2 * pi * 75 / 100) calc(40 * 2 * pi); fill: none; } } .text { position: absolute; top: 0; height: 100%; width: 100%; text-align: center; align-content: center; font-size: 120%; font-weight: bold; } }
SVG の <circle>
を用いてベースとなる円を描きます。
.pie-chart-box { .pie-chart { border: 1px solid #ddd; .chart-1 { stroke: #ddd; stroke-width: 4; fill: none; } } }
<div class="pie-chart-box"> <svg class="pie-chart" width="150" height="150"> <circle class="chart-1" cx="50%" cy="50%" r="40"></circle> </svg> </div>
ベース円の上に数値を示す円を描きます。
.pie-chart-box { .pie-chart { .chart-1 { ... } .chart-2 { stroke: #339; stroke-width: 8; fill: none; } } }
<div class="pie-chart-box"> <svg class="pie-chart" width="150" height="150"> <circle class="chart-1" cx="50%" cy="50%" r="40"></circle> <circle class="chart-2" cx="50%" cy="50%" r="40"></circle> </svg> </div>
storoke-dasharray
を用いて数値円を破線にします。第1引数は実線の長さ、第2引数は隙間の長さです。実線の長さを円周(半径40×2×π)の 75% にし、隙間の長さを十分大きな値(円周あれば十分)にすることで、長さ 75% の円弧を描くことができます。
.pie-chart-box { .pie-chart { .chart-1 { ... } .chart-2 { ... stroke-dasharray: calc(40 * 2 * pi * 75 / 100) calc(40 * 2 * pi); } } }
実践の開始点は右端になるので円グラフを -90度 回転させて上端から描画するようにします。
.pie-chart-box { .pie-chart { transform: rotate(-90deg); .chart-1 { ... } .chart-2 { ... } } }
テキストを円の中心に配置に表示します。
.pie-chart-box { position: relative; width: 150px; height: 150px; .pie-chart { ... } .text { position: absolute; top: 0; height: 100%; width: 100%; text-align: center; align-content: center; font-size: 120%; font-weight: bold; } }
<div class="pie-chart-box"> <svg class="pie-chart" width="150" height="150"> <circle class="chart-1" cx="50%" cy="50%" r="40"></circle> <circle class="chart-2" cx="50%" cy="50%" r="40"></circle> </svg> <div class="text">75%</div> </div>