【问题标题】:Chart.js turn labels into linksChart.js 将标签变成链接
【发布时间】:2015-04-30 16:52:05
【问题描述】:

如果不采取以下措施,我不确定这是否可行:Create links in HTML canvas,但让我们确定一下。

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

【问题讨论】:

  • 我相信您将不得不采用您提供的链接中的方式。这是因为 Chart.js 使用 canvas 元素来绘制包括其标签在内的所有内容。
  • 即使那个解决方案对我也没有好处,因为如果我理解正确,我只能拥有看起来像链接的链接 - 完整的 url,而不是用户友好的标签,其 href 对平均不可见用户。
  • 稍作改动就可以解决这个问题。您可以显示一个文本但存储与该文本对应的链接,当单击该项目时转到相应的链接位置。

标签: javascript chart.js


【解决方案1】:

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

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

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

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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-07
    • 2019-07-24
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多