Chart.js 将标签变成链接 [英] Chart.js turn labels into links

查看:18
本文介绍了Chart.js 将标签变成链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果不执行以下操作,我不确定这是否可行:在HTML 画布,但让我们确定一下.

I'm not sure this is possible without doing something along the line of: Create links in HTML canvas but let's make sure.

有没有办法(相对)简单地将 Chart.js 标签转换为链接?有问题的图表是雷达图:http://www.chartjs.org/docs/#雷达图(到目前为止,我一直在使用图例,只需稍加修改库即可正常工作,但现在我应该使用标签本身.)

Is there a way to (relatively) simply turn Chart.js labels into links? The chart in question is the radar chart: http://www.chartjs.org/docs/#radar-chart (So far I've been using the legend for that, works fine with a little library modification, but now I should use the labels themselves.)

推荐答案

你可以监听点击事件,然后遍历所有的pointLabels,检查点击是否在那个框内.如果是这种情况,您可以从包含所有标签的数组中获取相应的标签.

You can listen to the click event and then loop through all the pointLabels check if the click is in that box. If this is the case you get the corresponding label from the array containing all the labels.

然后你可以打开使用 window.location = linkwindow.open(link) 去你的链接.

Then you can open use window.location = link or window.open(link) to go to your link.

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

Example that searches the color on google on click:

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);

<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>

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

这篇关于Chart.js 将标签变成链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆