插件窝 干货文章 AntV/G6图表库中节点文字过长如何优雅显示省略号?

AntV/G6图表库中节点文字过长如何优雅显示省略号?

节点 graph 显示 省略号 244    来源:    2025-03-21

在AntV/G6图表库中,当节点的文字内容过长时,可以通过以下几种方式来优雅地显示省略号(...):

1. 使用 textellipsis 属性

G6 提供了 text 配置项,可以通过设置 ellipsis 属性来在文字过长时显示省略号。

const graph = new G6.Graph({
  container: 'mountNode',
  width: 800,
  height: 600,
  defaultNode: {
    type: 'circle',
    labelCfg: {
      style: {
        fill: '#333',
        fontSize: 14,
        // 设置 ellipsis 属性
        ellipsis: true,
        // 设置最大宽度
        maxWidth: 100,
      },
    },
  },
});

// 添加节点
graph.data({
  nodes: [
    {
      id: 'node1',
      label: '这是一个非常长的节点名称,需要显示省略号',
      x: 100,
      y: 100,
    },
  ],
});

graph.render();

2. 自定义 labelformatter

你可以通过自定义 labelformatter 函数来手动处理文字过长的情况。

const graph = new G6.Graph({
  container: 'mountNode',
  width: 800,
  height: 600,
  defaultNode: {
    type: 'circle',
    labelCfg: {
      style: {
        fill: '#333',
        fontSize: 14,
      },
      // 自定义 formatter
      formatter: (text) => {
        const maxLength = 10; // 最大显示长度
        return text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
      },
    },
  },
});

// 添加节点
graph.data({
  nodes: [
    {
      id: 'node1',
      label: '这是一个非常长的节点名称,需要显示省略号',
      x: 100,
      y: 100,
    },
  ],
});

graph.render();

3. 使用 textWraptextMaxLine

如果你希望文字在超出一定宽度时自动换行,并且只显示指定行数,可以使用 textWraptextMaxLine 属性。

const graph = new G6.Graph({
  container: 'mountNode',
  width: 800,
  height: 600,
  defaultNode: {
    type: 'circle',
    labelCfg: {
      style: {
        fill: '#333',
        fontSize: 14,
        // 设置自动换行
        textWrap: true,
        // 设置最大行数
        textMaxLine: 2,
        // 设置最大宽度
        maxWidth: 100,
      },
    },
  },
});

// 添加节点
graph.data({
  nodes: [
    {
      id: 'node1',
      label: '这是一个非常长的节点名称,需要显示省略号',
      x: 100,
      y: 100,
    },
  ],
});

graph.render();

4. 使用 tooltip 显示完整内容

如果文字过长,可以在鼠标悬停时通过 tooltip 显示完整内容。

const graph = new G6.Graph({
  container: 'mountNode',
  width: 800,
  height: 600,
  defaultNode: {
    type: 'circle',
    labelCfg: {
      style: {
        fill: '#333',
        fontSize: 14,
        ellipsis: true,
        maxWidth: 100,
      },
    },
  },
  modes: {
    default: ['drag-node', 'zoom-canvas'],
    // 启用 tooltip
    tooltip: {
      formatText(model) {
        return model.label;
      },
    },
  },
});

// 添加节点
graph.data({
  nodes: [
    {
      id: 'node1',
      label: '这是一个非常长的节点名称,需要显示省略号',
      x: 100,
      y: 100,
    },
  ],
});

graph.render();

总结

  • ellipsis 属性:简单直接,适合大多数场景。
  • 自定义 formatter:灵活控制,适合需要自定义逻辑的场景。
  • textWraptextMaxLine:适合需要多行显示的场景。
  • tooltip:适合需要在悬停时显示完整内容的场景。

根据你的具体需求选择合适的方式来实现节点文字的优雅显示。