Chart.js将标签转换为链接

dnm*_*nmh 7 javascript chart.js

我不确定如果不做以下事情就可以做到这一点:在HTML画布中创建链接,但让我们确定.

有没有办法(相对)简单地将Chart.js标签变成链接?有问题的图表是雷达图:http://www.chartjs.org/docs/#radar-chart (到目前为止,我一直在使用这个图例,通过一些小的库修改工作正常,但现在我应该自己使用标签.)

Lee*_*lee 1

您可以侦听单击事件,然后循环遍历所有 pointLabels 检查单击是否在该框中。如果是这种情况,您可以从包含所有标签的数组中获取相应的标签。

然后您就可以打开使用window.location = linkwindow.open(link)转到您的链接。

点击后在谷歌上搜索颜色的示例:

const options = {
  type: 'radar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'orange'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'pink'
      }
    ]
  },
  options: {
    onClick: (evt, activeEls, chart) => {
      const {
        x,
        y
      } = evt;
      let index = -1;

      for (let i = 0; i < chart.scales.r._pointLabelItems.length; i++) {
        const {
          bottom,
          top,
          left,
          right
        } = chart.scales.r._pointLabelItems[i];

        if (x >= left && x <= right && y >= top && y <= bottom) {
          index = i;
          break;
        }
      }

      if (index === -1) {
        return;
      }

      const clickedLabel = chart.scales.r._pointLabels[index];

      window.open(`https://www.google.com/search?q=color%20${clickedLabel}`); // Blocked in stack snipet. See fiddle
      console.log(clickedLabel)
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
Run Code Online (Sandbox Code Playgroud)
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)

小提琴:https://jsfiddle.net/Leelenaleee/fnqr4c7j/22/