在chartjs中从一个条到另一个条绘制点线

xv8emn3q  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(135)

我想创建线连接后,酒吧与下一个酒吧之前,如图像下

kdfy810k

kdfy810k1#

您可以使用custom chartjs plugin创建线连接器,然后使用chartjs提供的canvas在beforeDatasetsDraw回调上绘制线,
使用bar._model.y获取每个条形图的顶部位置
使用bar._model.base获取每个条形图的底部位置

var options = {
  type: 'bar',
  data: {
    labels: ["a", "b", "c", "d", "e", "f"],
    datasets: [
        {
          label: 'A',
          data: [[12,14], [14,24],[10,12]],
        borderWidth: 1
        },
        ]
  },
  options: {
    scales: {
        yAxes: [{
        ticks: {
                    reverse: false
        }
      }]
    }
  }
}


const barConnector = {
  id: 'barConnector',
  beforeDatasetsDraw: function(chart, args, plugins){
    const { ctx, chartArea } = chart;
    ctx.save();
    const datasets = chart.config.data.datasets;

    datasets.forEach((dataset, datasetIndex) => {
      dataset.data.forEach((data, dataIndex) => {
        if(dataIndex === dataset.data.length - 1) return;
        const bar = chart.getDatasetMeta(datasetIndex).data[dataIndex];
        const barX = bar._model.x;
        const barY = bar._model.y;

        const nextBar = chart.getDatasetMeta(datasetIndex).data[dataIndex + 1];
        const nextBarX = nextBar?._model.x;
        const nextBarY = nextBar?._model.base;
        
        ctx.beginPath();
        ctx.moveTo(barX+46, barY);
        ctx.lineTo(nextBarX-46, nextBarY);
        ctx.strokeStyle = dataset.backgroundColor;
        ctx.lineWidth = 2;
        ctx.stroke();
      })
    });
  }
}

options.plugins = [barConnector]

var ctx = document.getElementById('chart-js').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>
    <canvas id="chart-js" width="600" height="400"></canvas>
</body>

相关问题