插件窝 干货文章 如何用AntV G6或X6实现复杂流程图的可视化?

如何用AntV G6或X6实现复杂流程图的可视化?

node 流程图 label container 587    来源:    2025-03-20

使用AntV G6或X6实现复杂流程图的可视化涉及多个步骤,包括数据准备、图形配置、交互设计等。以下是使用这两个库实现复杂流程图可视化的基本步骤和示例代码。

使用AntV G6实现复杂流程图

1. 安装G6

首先,确保你已经安装了G6。如果没有安装,可以使用npm或yarn进行安装:

npm install @antv/g6

2. 准备数据

G6需要一个符合其数据格式的JSON对象来描述流程图。通常,这个JSON对象包含nodesedges两个数组。

const data = {
  nodes: [
    { id: 'node1', x: 100, y: 100, label: 'Start' },
    { id: 'node2', x: 300, y: 100, label: 'Process 1' },
    { id: 'node3', x: 500, y: 100, label: 'Process 2' },
    { id: 'node4', x: 300, y: 300, label: 'End' },
  ],
  edges: [
    { source: 'node1', target: 'node2' },
    { source: 'node2', target: 'node3' },
    { source: 'node3', target: 'node4' },
  ],
};

3. 创建图实例并渲染

使用G6创建图实例,并将数据渲染到页面上。

import G6 from '@antv/g6';

const container = document.getElementById('container');
const width = container.scrollWidth;
const height = container.scrollHeight || 500;

const graph = new G6.Graph({
  container: 'container',
  width,
  height,
  modes: {
    default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
  },
  defaultNode: {
    type: 'circle',
    size: [80],
    style: {
      fill: '#C6E5FF',
      stroke: '#5B8FF9',
    },
    labelCfg: {
      style: {
        fill: '#000',
      },
    },
  },
  defaultEdge: {
    type: 'line',
    style: {
      stroke: '#A3B1BF',
    },
  },
});

graph.data(data);
graph.render();

使用AntV X6实现复杂流程图

1. 安装X6

首先,确保你已经安装了X6。如果没有安装,可以使用npm或yarn进行安装:

npm install @antv/x6

2. 准备数据

X6同样需要一个符合其数据格式的JSON对象来描述流程图。

const data = {
  nodes: [
    { id: 'node1', x: 40, y: 40, width: 80, height: 40, label: 'Start' },
    { id: 'node2', x: 200, y: 40, width: 80, height: 40, label: 'Process 1' },
    { id: 'node3', x: 360, y: 40, width: 80, height: 40, label: 'Process 2' },
    { id: 'node4', x: 200, y: 200, width: 80, height: 40, label: 'End' },
  ],
  edges: [
    { source: 'node1', target: 'node2' },
    { source: 'node2', target: 'node3' },
    { source: 'node3', target: 'node4' },
  ],
};

3. 创建图实例并渲染

使用X6创建图实例,并将数据渲染到页面上。

import { Graph } from '@antv/x6';

const graph = new Graph({
  container: document.getElementById('container'),
  width: 800,
  height: 600,
  grid: true,
});

data.nodes.forEach(node => {
  graph.addNode({
    id: node.id,
    x: node.x,
    y: node.y,
    width: node.width,
    height: node.height,
    label: node.label,
    attrs: {
      body: {
        fill: '#C6E5FF',
        stroke: '#5B8FF9',
      },
      label: {
        fill: '#000',
      },
    },
  });
});

data.edges.forEach(edge => {
  graph.addEdge({
    source: edge.source,
    target: edge.target,
    attrs: {
      line: {
        stroke: '#A3B1BF',
      },
    },
  });
});

总结

无论是使用G6还是X6,实现复杂流程图可视化的基本步骤都是相似的:准备数据、配置图形、创建图实例并渲染。G6和X6都提供了丰富的API和配置项,可以根据具体需求进行定制和扩展。

  • G6 更适合需要高度定制化和复杂交互的场景。
  • X6 则更适合需要快速搭建流程图、且对交互要求不高的场景。

根据你的具体需求选择合适的库,并参考官方文档进行更深入的定制和优化。