Line Chartでsection毎に背景色を付ける
やりたいこと with chart.js
パターン1: datasetsをsection毎の配列で渡す
https://stackoverflow.com/questions/52120036/chartjs-line-color-between-two-points
パターン2: ライブラリに描画ロジックを追加 ※ライブラリにロジック追加は微妙 https://github.com/chartjs/Chart.js/issues/4068
実装例(パターン1)
※ https://codepen.io/chartjs/pen/YVWZbz で試す
HTML
<div class="chart-container"> <canvas id="chart"></canvas> </div>
body { background: #1D1F20; padding: 16px; } canvas { border: 1px dotted red; } .chart-container { position: relative; margin: auto; height: 80vh; width: 80vw; }
const ctx = document.getElementById('chart').getContext('2d'); const data = { labels: ["Step1", "Step2", "Step3", "Step4", "Step5"], datasets: [{ // ★★★section毎にbackgroundColorを設定して渡す★★★ data: [100, 80, NaN, NaN, NaN], backgroundColor: '#0000FF', lineTension: 0, pointRadius: 0, } , { data: [NaN, 80, 60, NaN, NaN], backgroundColor: '#FFFF00', lineTension: 0, pointRadius: 0, }, { data: [NaN, NaN, 60, 40, NaN], backgroundColor: '#008000', lineTension: 0, pointRadius: 0, }, { data: [NaN, NaN, NaN, 40, 20], backgroundColor: '#FF0000', lineTension: 0, pointRadius: 0, } ] }; const options = { maintainAspectRatio: false, scales: { xAxes: [{ gridLines: { // 目盛線 display: true, color: "grey", }, ticks: { // 目盛り display: false, }, }], yAxes: [{ display: false, ticks: { // 目盛り display: false, beginAtZero: true, }, }] }, legend: { // ラベル display: false }, }; const myChart = new Chart(ctx, { type: 'line', data: data, options: options, });