如何在ChartJS中创建此图表?在NEXTjs与TSX

jjjwad0x  于 2023-08-05  发布在  Chart.js
关注(0)|答案(1)|浏览(154)

enter image description here
你好
我如何使用chartjs创建这个图表我已经尝试使用浮动栏,但其余地区的酒吧,我不能得到它的阴影。请让我知道
我真的很感激
这是数据

const dayData = [
    {
        date: "2021-09-01",
        timesExercised: {
            exercise1: {
                startTime: "2021-09-01T09:00:00",
                endTime: "2021-09-01T09:30:00"
            },
            exercise2: {
                startTime: "2021-09-01T10:00:00",
                endTime: "2021-09-01T10:30:00"
            }
        }
    },
    {
        date: "2021-09-02",
        timesExercised: {
            exercise1: {
                startTime: "2021-09-02T09:00:00",
                endTime: "2021-09-02T09:30:00"
            },
            exercise2: {
                startTime: "2021-09-02T10:00:00",
                endTime: "2021-09-02T10:30:00"
            }
        }
    }
];

字符串

icnyk63a

icnyk63a1#

要实现您发布的图表,您需要一个自定义插件。
这里是一个示例:

const labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const rndMinMax = (min, max) => Math.floor(Math.random() * (max - min)) + min;
const getData = () => {
  const start = rndMinMax(0, 12);
  const end = rndMinMax(start, 24);
  return [start, end];
}

const plugin = {
  id: 'barShadowing',
  beforeDatasetDraw(chart, args, options) {
    const ctx = chart.ctx
    const meta = args.meta;
    const yScale = meta.yScale;
    const {top, bottom} = yScale;
    ctx.save();
    meta.data.forEach(function(element, i) {
      const {x, width, options} = element;
      const shadow = {
        x: x - (width / 2),
        w: width,
        y: top,
        h: bottom - top,
        radius: Chart.helpers.toTRBLCorners(options.borderRadius)
      };
      ctx.beginPath();
      ctx.fillStyle = 'rgb(196, 219, 239)';
      Chart.helpers.addRoundedRectPath(ctx, shadow);
      ctx.fill();
    });
    ctx.restore();
  }
}

const config = {
  type: 'bar',
  plugins: [plugin],
  data: {
    labels,
    datasets: [{
      label: "My First dataset",
      data: labels.map(() => getData()),
      categoryPercentage: 0.25,
      backgroundColor: 'rgb(17, 116, 236)',
      borderRadius: 8,
      borderSkipped: false
    }]
  },
  options: {
    plugins: {
      legend: false
    },
    scales: {
      x: {
        grid: {
          display: false
        },
        ticks: {
          font: {
            size: 16
          }
        }
      },
      y: {
        min: 0,
        max: 24,
        ticks: {
          font: {
            size: 16
          },
          stepSize: 4,
          callback: (value) => value + ':00'
        }
      }
    }
  }
};

const ctx = document.getElementById("myChart").getContext("2d");
const myChart = new Chart(ctx, config);
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://npmcdn.com/chart.js@latest/dist/chart.umd.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

相关问题