插件窝 干货文章 AntV/G6 Dagre布局下,节点文字过长如何优雅显示省略号?

AntV/G6 Dagre布局下,节点文字过长如何优雅显示省略号?

节点 文字 ellipsis const 124    来源:    2025-03-21

在AntV/G6中使用Dagre布局时,如果节点文字过长,可以通过以下几种方式优雅地显示省略号:

1. 使用CSS样式控制文字显示

你可以通过CSS样式来控制节点文字的显示方式,使其在超出一定宽度时显示省略号。具体步骤如下:

const graph = new G6.Graph({
  container: 'mountNode',
  width: 800,
  height: 600,
  defaultNode: {
    type: 'rect',
    labelCfg: {
      style: {
        fontSize: 12,
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
        width: '100px', // 设置一个固定的宽度
      },
    },
  },
  layout: {
    type: 'dagre',
    rankdir: 'LR', // 布局方向,可选 'TB', 'BT', 'LR', 'RL'
    align: 'DL', // 对齐方式
    nodesep: 50, // 节点间距
    ranksep: 100, // 层级间距
  },
});

2. 使用自定义节点

如果你需要更复杂的控制,可以通过自定义节点来实现。在自定义节点中,你可以使用<text>元素的textLengthlengthAdjust属性来控制文字的显示。

G6.registerNode('custom-node', {
  draw(cfg, group) {
    const width = 100; // 节点宽度
    const height = 40; // 节点高度

    const rect = group.addShape('rect', {
      attrs: {
        x: 0,
        y: 0,
        width,
        height,
        fill: '#fff',
        stroke: '#000',
      },
    });

    const text = group.addShape('text', {
      attrs: {
        x: width / 2,
        y: height / 2,
        text: cfg.label,
        textAlign: 'center',
        textBaseline: 'middle',
        fontSize: 12,
        fill: '#000',
        textLength: width - 10, // 设置文字长度
        lengthAdjust: 'spacingAndGlyphs', // 调整文字间距和字形
      },
    });

    return rect;
  },
});

const graph = new G6.Graph({
  container: 'mountNode',
  width: 800,
  height: 600,
  defaultNode: {
    type: 'custom-node',
  },
  layout: {
    type: 'dagre',
    rankdir: 'LR',
    align: 'DL',
    nodesep: 50,
    ranksep: 100,
  },
});

3. 使用ellipsis插件

如果你使用的是G6的较新版本,可以考虑使用ellipsis插件来自动处理文字过长的问题。

import G6 from '@antv/g6';
import { Ellipsis } from '@antv/g6-plugin-ellipsis';

const ellipsis = new Ellipsis({
  maxWidth: 100, // 最大宽度
  ellipsis: '...', // 省略号
});

const graph = new G6.Graph({
  container: 'mountNode',
  width: 800,
  height: 600,
  plugins: [ellipsis],
  defaultNode: {
    type: 'rect',
    labelCfg: {
      style: {
        fontSize: 12,
      },
    },
  },
  layout: {
    type: 'dagre',
    rankdir: 'LR',
    align: 'DL',
    nodesep: 50,
    ranksep: 100,
  },
});

4. 动态调整文字长度

如果你希望在运行时动态调整文字长度,可以在节点更新时重新计算文字长度并设置省略号。

graph.on('node:click', (evt) => {
  const node = evt.item;
  const model = node.getModel();
  const label = model.label;

  // 动态调整文字长度
  if (label.length > 10) {
    model.label = label.substring(0, 10) + '...';
    graph.updateItem(node, model);
  }
});

总结

通过以上几种方式,你可以在AntV/G6的Dagre布局中优雅地处理节点文字过长的问题,使其显示省略号。具体选择哪种方式取决于你的需求和项目的复杂度。