毕设在使用antv x6做前端,记录一下踩坑日记。
先根据官方文档,写一个最简demo:
App.vue
import {onMounted} from "vue";
import {Graph} from "@antv/x6";
onMounted(()=>{
const graph=new Graph(({
container: document.getElementById('graph-container'),
autoResize:true,
background:{
color: '#F2F7FA'
},
panning:true,
}))
graph.fromJSON(data);
graph.centerContent();
})
//data省略,可以去官方文档复制
const data = {...}
<template>
<div class="app-container">
<div style="width: 100%;height: 100px;background-color: red;"></div>
<div class="graph-parent">
<div style="width: 100%;height: 100%" id="listener">
<div id="graph-container"></div>
</div>
</div>
</div>
</template>
<style scoped>
.app-container {
width: 100vw;
height: 100vh;
}
.graph-parent{
width: 100%;
height: 500px;
background-color: aqua;
}
</style>
展示结果:
(红色div用于模拟页面其他元素)
可以看到,拓扑节点在垂直方向上不居中,在水平方向上居中。经过多次实验,发现在onMounted的时候graph-container 块宽度为100%,高度为0。
根本原因在于new Graph时没有设置宽高,以画布容器大小初始化画布,而画布容器内容为空,高度为0。
官方文档说明:
给画布容器加上height:100%即可解决问题
<div id="graph-container" style="height:100%" />
出现这个问题的原因在于本人被官方文档误导,以为加了autoResize就不需要再为画布容器设置宽高,以为会自动根据外层容器尺寸初始化画布容器。
猜测实际上的执行流程为:
- 以空div的尺寸,即height:0;width:100%;初始化画布。
- graph.centerContent(),导致水平居中,垂直方向上因为height为0所以到了容器最上端。
- 监听外层容器尺寸,改变画布大小为外层容器尺寸,导致出现最终展示效果。