最近使用Vue開發中,需要實作流程圖的編輯和繪制,發現了一款好用的圖編輯架構antv x6 點選檢視官網api
安裝
通過 npm 或 yarn 指令安裝 X6。
# npm
$ npm install @antv/x6 --save
# yarn
$ yarn add @antv/x6
使用
<!--繪圖面闆元件-->
<div id="container" class="x6-graph"/>
// 導入 Graph
import { Graph } from '@antv/x6';
// 初始化面闆
const graph = new Graph({
container: document.getElementById('container'),
width: 800,
height: 600,
// 格子屬性
grid: {
size: 10,// 網格大小 10px
visible: true,// 渲染網格背景
type: 'dot',// 網格類型
},
});
const data = {
// 節點
nodes: [
{
id: 'node1', // String,可選,節點的唯一辨別
x: 40, // Number,必選,節點位置的 x 值
y: 40, // Number,必選,節點位置的 y 值
width: 80, // Number,可選,節點大小的 width 值
height: 40, // Number,可選,節點大小的 height 值
label: 'hello', // String,節點标簽
},
],
// 邊
edges: [
{
source: 'node1', // String,必須,起始節點 id
target: 'node2', // String,必須,目标節點 id
},
],
};
// 渲染節點資料
graph.fromJSON(data)
實際項目
效果圖
vue項目結構
開發步驟
流程圖元件結構
建立graph檔案初始化流程圖相關配置 多餘代碼...源碼到git下載下傳
- data.js 存放初始化流程圖資料
const graphData = {
cells: [
{
// 設定節點位置
position: {
x: 420,
y: 40
},
size: {
width: 80,// 節點 widrth 值
height: 42// 節點 height 值
},
// 設定節點樣式
attrs: {
text: {
text: '開始',
nodeType: 'start'
}
},
shape: 'flow-chart-rect',
zIndex: 1
},
}
export default graphData
- shape.js 存放節點庫的節點配置
注意:
1.自定義節點的時候,圖檔引入通過require導入
2.ports:連結樁是節點上的固定連接配接點。很多圖應用都有連結樁,并且有些應用還将連結樁分為輸傳入連結接樁和輸出連接配接樁。
建節點時我們可以通過
選項來配置連結樁,像下面這樣:
ports
ports: { groups: { ... }, // 連結樁組定義 items: [ ... ], // 連結樁 } // 或者 ports: [ ... ], // 連結樁
import { Graph, Dom, Node } from '@antv/x6'
export const ChartH5Rect = Graph.registerNode('flow-H5-rect', {
inherit: 'rect',
...
attrs: {
body: {...},
image: {
'xlink:href':
require('../../../assets/h5.png'),
...
}
},
markup: [
...
{
tagName: 'image',
selector: 'image'
},
],
ports: {
groups: {...},
items: [
{
group: 'top'
},
...
]
}
})
Graph.registerNode('groupNode', NodeGroup)
- index.js初始化流程圖和渲染資料
注意:
1.grid是網格,
2.selecting内是點選/框選,預設禁用。建立畫布時,通過selecting的配置開啟選擇互動,開啟後可以通過點選或者套索框選節點。
3.connecting:配置全局的連線規則
import { Graph, FunctionExt, Shape, Addon } from '@antv/x6'
import './shape'
import graphData from './data'
export default class FlowGraph {
// 類構造方法
constructor () {
this.initGraph()
this.initStencil()
this.initEvent()
}
initGraph () {// 初始化面闆
this.graph = new Graph({
container: document.getElementById('container'),
// 格子屬性
grid: {...},
selecting: {....},
connecting: {....},
})
}
initStencil () { // 初始化左側元件
this.stencil = new Addon.Stencil({
target: this.graph,
...
})
}
initGraphShape () { // 面闆渲染
this.graph.fromJSON(graphData)
}
initEvent () {// 初始化事件
...
}
}
在頁面中建立用于容納 X6 繪圖的容器元素
1.stencil 左側節點庫
2.panel 操作欄
3.container畫布
<!--左側工具欄-->
<div id="stencil" class="sider"></div>
<div class="panel">
<div class="toolbar">
<tool-bar :flowGraph="flowGraph" />
</div>
</div>
<!--繪圖面闆元件-->
<div id="container" class="x6-graph"/></div>
<!--配置面闆元件:傳遞flowGraph給子元件使用-->
<div class="config">
<config-panel :flowGraph="flowGraph"/>
</div>