返回

G2 图表 4.x 版本图例不再支持单选模式?别慌!有方法解决

前端

在 G2 图表的最新版本中,图例不再支持单选模式,这一改动给许多习惯使用单选模式的用户带来了困扰。然而,仔细研究 G2 图表的文档,我们可以找到解决这个问题的办法。

方法一:使用 HTML 元素模拟单选模式

我们可以使用 HTML 元素来模拟单选模式。具体做法是,在图例的每一项中添加一个 input 元素,并将其 type 属性设置为 radio。这样,当用户点击图例中的某一项时,就会自动选中该项,同时取消其他项的选中状态。

<div id="legend">
  <input type="radio" name="legend-item" value="item1">
  <label for="item1">Item 1</label>
  <input type="radio" name="legend-item" value="item2">
  <label for="item2">Item 2</label>
  <input type="radio" name="legend-item" value="item3">
  <label for="item3">Item 3</label>
</div>
// 获取图例元素
const legend = document.getElementById('legend');

// 为每个图例项添加事件监听器
legend.querySelectorAll('input[type="radio"]').forEach(item => {
  item.addEventListener('change', function() {
    // 取消其他项的选中状态
    legend.querySelectorAll('input[type="radio"]').forEach(item2 => {
      if (item2 !== this) {
        item2.checked = false;
      }
    });

    // 触发图表的更新
    chart.update();
  });
});

方法二:使用 G2 的自定义图例组件

G2 还提供了一个自定义图例组件,可以用来实现单选模式。具体做法是,在图表的配置项中,将 legend.type 设置为 'custom',然后在 legend.custom 中指定自定义的图例组件。

const chart = new G2.Chart({
  container: 'mountNode',
  width: 400,
  height: 300
});

chart.source(data);
chart.interval().position('x*y').color('type');

chart.legend({
  type: 'custom',
  custom: {
    html: '<div id="legend"></div>',
    position: 'bottom',
    align: 'center',
    itemWidth: 100,
    itemHeight: 20,
    itemMargin: [10, 10],
    padding: [10, 10],
    background: {
      fill: '#fff',
      stroke: '#ccc',
      lineWidth: 1
    },
    item: {
      selectedMode: 'single',
      onClick: function(item) {
        // 取消其他项的选中状态
        legend.querySelectorAll('input[type="radio"]').forEach(item2 => {
          if (item2 !== this) {
            item2.checked = false;
          }
        });

        // 触发图表的更新
        chart.update();
      }
    }
  }
});

chart.render();

这两种方法都可以实现 G2 图表 4.x 版本中的图例单选功能,开发者可以根据自己的需要选择合适的方法。