【问题标题】:ChartJS - Moving vertical line is display on top of tooltipChartJS - 移动垂直线显示在工具提示顶部
【发布时间】:2021-07-28 07:16:20
【问题描述】:

你好,

我已经关注了这篇文章 (Moving vertical line when hovering over the chart using chart.js) 在我的图表上画了一条垂直线。

使用单个数据集,它工作得很好。

但对于多个数据集显示(在 y 轴上具有堆叠选项),垂直线会绘制在图表的工具提示上。

设置图表工具提示的 z-index 和垂直线都不能解决我的问题。因为我找不到任何属性来做到这一点。

您有解决此问题的任何想法/建议吗?

我正在使用 react-chart-js 2 和 chart-js ^2.9.4 作为对等依赖项。

【问题讨论】:

    标签: javascript typescript frontend chart.js react-chartjs-2


    【解决方案1】:

    您可以使用自定义插件,在绘制所有数据集之后但在绘制工具提示之前绘制:

    var options = {
      type: 'line',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            borderWidth: 1
          },
          {
            label: '# of Points',
            data: [7, 11, 5, 8, 3, 7],
            borderWidth: 1
          }
        ]
      },
      options: {
        scales: {
          yAxes: [{
            stacked: true
          }]
        },
        plugins: {
          customLine: {
            width: 5,
            color: 'pink'
          }
        }
      },
      plugins: [{
        id: 'customLine',
        afterDatasetsDraw: (chart, x, opts) => {
          const width = opts.width || 1;
          const color = opts.color || 'black'
    
          if (!chart.active || chart.active.length === 0) {
            return;
          }
    
          const {
            chartArea: {
              top,
              bottom
            }
          } = chart;
          const xValue = chart.active[0]._model.x
    
          ctx.lineWidth = width;
          ctx.strokeStyle = color;
    
          ctx.beginPath();
          ctx.moveTo(xValue, top);
          ctx.lineTo(xValue, bottom);
          ctx.stroke();
        }
      }]
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
    </body>

    【讨论】:

    • 感谢您的建议。 afterDatasetDraw 钩子解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多