安装:
npm i @antv/x6 --save
引入:
import { Graph } from ‘@antv/x6’;
在页面创建一个流程图容器,例如div:
<div id="container" style="position: relative"></div>
创建流程图需要节点nodes、边edges:
const data = {
// 节点
nodes: [
{
id: 'node1', // String,可选,节点的唯一标识
x: 100, // Number,必选,节点位置的 x 值
y: 100, // Number,必选,节点位置的 y 值
width: 80, // Number,可选,节点大小的 width 值
height: 40, // Number,可选,节点大小的 height 值
// size: [300,200],
label: 'start', // String,节点标签
},
{
id: 'node2', // String,节点的唯一标识
shape: 'ellipse', // 节点形状,默认节点。也可以自定义节点,自定义如下
x: 100, // Number,必选,节点位置的 x 值
y: 200, // Number,必选,节点位置的 y 值
width: 80, // Number,可选,节点大小的 width 值
height: 40, // Number,可选,节点大小的 height 值
label: 'next', // String,节点标签
attrs: {
body: {
fill: '#0f0', // 标签填充色
},
label: {
// text: 'word', // 标签文字内容
fill: '#09f', // 标签颜色
},
}
},
{
id: 'node3', // String,节点的唯一标识
shape: 'lane-rect', // 节点形状,自定义节点,需要注册节点
x: 200, // Number,必选,节点位置的 x 值
y: 200, // Number,必选,节点位置的 y 值
width:80, // Number,可选,节点大小的 width 值
height: 40, // Number,可选,节点大小的 height 值
label: 'end', // String,节点标签
},
],
// 边
edges: [
{
source: 'node1', // String,必须,起始节点 id
target: 'node2', // String,必须,目标节点 id
},
{
source: 'node2', // String,必须,起始节点 id
target: 'node3', // String,必须,目标节点 id
vertices: [
{ x: 420, y: 210 }, // 边线经过的位置。可设置一个或多个位置。
],
},
],
};
注册自定义节点:
// 注意: 自定义节点只能注册一次,重复注册会报错。注册节点需要放到节点之前执行。
Graph.registerNode(
'lane',
{
inherit: 'rect',
markup: [
{
tagName: 'rect',
selector: 'body',
},
{
tagName: 'rect',
selector: 'name-rect',
},
{
tagName: 'text',
selector: 'name-text',
},
],
attrs: {
body: {
fill: '#FFF',
stroke: '#5F95FF',
strokeWidth: 1,
},
name-rect': {
width: 300,
height: 30,
fill: '#5F95FF',
stroke: '#fff',
strokeWidth: 1,
x: -1,
},
'name-text': {
ref: 'name-rect',
refY: 0.5,
refX: 0.5,
textAnchor: 'middle',
fontWeight: 'bold',
fill: '#fff',
fontSize: 12,
},
},
},
true,
)
Graph.registerNode(
'lane-rect',
{
inherit: 'rect',
width: 160,
height: 80,
attrs: {
body: {
strokeWidth: 1,
stroke: '#5F95FF',
fill: '#EFF4FF',
},
text: {
fontSize: 12,
fill: '#262626',
},
},
},
true,
)
Graph.registerNode(
'lane-polygon',
{
inherit: 'polygon',
width: 160,
height: 100,
attrs: {
body: {
strokeWidth: 1,
stroke: '#5F95FF',
fill: '#EFF4FF',
refPoints: '0,10 10,0 20,10 10,20',
},
text: {
fontSize: 12,
fill: '#262626',
},
},
},
true,
)
Graph.registerEdge(
'lane-edge',
{
inherit: 'edge',
attrs: {
line: {
stroke: '#09f',
strokeWidth: 2,
},
},
label: {
attrs: {
label: {
fill: '#A2B1C3',
fontSize: 12,
},
},
},
},
true,
)
渲染画布:
// 创建一个 Graph 对象
const graph = new Graph({
container: document.getElementById('container'),
interacting: {
nodeMovable: false,
},
});
// Graph 对象,渲染节点和边
graph.fromJSON(data)