官网地址:简介 | X6
一、npm安装
提示:这里使用的antv/x6 低版本1.XX.X
# npm
$ npm install @antv/x6 --save
二、使用
1.引入库
import { Graph} from "@antv/x6";
2.简单创建画布
<template>
<div class="visual-box">
<div id="container"></div>
</div>
</template>
<script>
import { Graph } from "@antv/x6";
export default {
name: "Construction",
data() {
return {};
},
mounted() {
this.initGraph();
},
methods: {
initGraph() {
const graph = new Graph({
container: document.getElementById("container"), // 画布容器id
panning: true, // 画布支持拖拽平移
autoResize: true, // 监听容器大小改变
mousewheel: true, //鼠标滚轮缩放
background: {
color: "#F5F7FA",
},
grid: {
size: 10,
visible: true,
},
});
graph.centerContent();
},
},
};
</script>
<style lang="scss" scoped>
.visual-box {
height: 94vh;
}
#container {
width: 100% !important;
height: 100% !important;
}
</style>
3.渲染和导出
(1)使用graph.fromJSON({ cells: [...] }):会根据shape属性自动识别节点和边,并按照数组顺序渲染
注意事项: 数据的格式固定且需要符合图形库要求
this.graph.fromJSON([
{
id: 'node1',
x: 40,
y: 40,
width: 100,
height: 40,
label: 'Hello',
shape: 'rect',
},
{
id: 'node2',
x: 200,
y: 40,
width: 100,
height: 40,
label: 'World',
shape: 'ellipse',
},
{
id: 'edge1',
source: 'node1',
target: 'node2',
shape: 'dag-edge',
}
]);
或者提供一个包含 cells
、nodes
、edges
的对象,按照 [...cells, ...nodes, ...edges]
顺序渲染。
this.graph.fromJSON({
nodes: [
{ id: "node1", shape: "rect", x: 100, y: 100, width: 220, height: 60 },
{ id: "node2", shape: "rect", x: 300, y: 100, width: 220, height: 60 },
],
edges: [
{ id: "edge1", shape: "dag-edge", source: "node1", target: "node2" },
],
})
(2)手动创建节点和边的方法:手动调用 creatNode和creatEdge
init(data = []) {
const cells = [];
data.forEach((item) => {
if (item.shape === "dag-edge") {
cells.push(this.graph.createEdge(item));
} else {
cells.push(this.graph.createNode(item));
}
});
this.graph.resetCells(cells);
}
const data = [
{ id: "node1", shape: "rect", x: 100, y: 100, width: 80, height: 40 },
{ id: "node2", shape: "rect", x: 300, y: 100, width: 80, height: 40 },
{ id: "edge1", shape: "dag-edge", source: "node1", target: "node2" },
];
init(data);
总结
-
fromJSON
:适合数据格式固定、初始化逻辑简单的场景,代码简洁且性能较高。 -
手动创建节点和边:适合需要动态调整数据或复杂逻辑的场景,灵活性更高。
(3)graph.toJSON() 方法导出图中的节点和边
导出格式如下:
{
cell: [
{
id: "node1",
shape: "rect",
position: { x: 100, y: 100 },
size: { width: 80, height: 40 },
attrs: {},
zIndex: number,
},
{
id: "node2",
shape: "rect",
position: { x: 100, y: 100 },
size: { width: 80, height: 40 },
attrs: {},
zIndex: number,
},
{
id: "edge1",
shape: "dag-edge",
source: "node1",
target: "node2",
attrs: {},
zIndex: number,
},
],
},