首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得已被单击的条形图标签的索引- js-2?

如何获得已被单击的条形图标签的索引- js-2?
EN

Stack Overflow用户
提问于 2022-02-15 11:08:13
回答 1查看 450关注 0票数 0

我尝试了文档中提供的事件,以及一些答案中的一些建议,但它们只在单击栏时才起作用,而不是在标签上。当我单击标签时,我只得到"element“上的一个空数组。

下面是对我起作用的方法,它与单击数据栏不同,但在标签单击中不起作用:

代码语言:javascript
复制
setOptions({
  ...
  onClick: function (evt, element) {
    // Get the index clicked:
    const index = element[0]?.index;
  },
});

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2022-02-15 17:42:14

您可以使用自定义插件来实现这一点:

代码语言:javascript
复制
const findLabel = (labels, evt) => {
  let found = false;
  let res = null;

  labels.forEach(l => {
    l.labels.forEach(label => {
      if (evt.x > label.x && evt.x < label.x2 && evt.y > label.y && evt.y < label.y2) {
        res = {
          label: label.label,
          index: label.index
        };
        found = true;
      }
    });
  });

  return [found, res];
};

const getLabelHitboxes = (scales) => (Object.values(scales).map((s) => ({
  scaleId: s.id,
  labels: s._labelItems.map((e, i) => ({
    x: e.translation[0] - s._labelSizes.widths[i] / 2,
    x2: e.translation[0] + s._labelSizes.widths[i] / 2,
    y: e.translation[1] - s._labelSizes.heights[i] / 2,
    y2: e.translation[1] + s._labelSizes.heights[i] / 2,
    label: e.label,
    index: i
  }))
})));

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {},
  plugins: [{
    id: 'customHover',
    afterEvent: (chart, event, opts) => {
      const evt = event.event;

      if (evt.type !== 'click') {
        return;
      }

      const [found, labelInfo] = findLabel(getLabelHitboxes(chart.scales), evt);

      if (found) {
        console.log(labelInfo);
      }

    }
  }]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
代码语言:javascript
复制
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71125407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档