官网: X6·图编辑引擎
支持节点和边的操作,包括拖拽、对齐等。如果你想在拖动节点时自动进行水平或垂直对齐,你可以通过监听节点的拖动事件,并计算节点之间的相对位置来实现。
- 监听节点的
node:moved
/node:dragging
事件,这个事件会在节点拖动时触发。 - 在事件处理函数中,获取所有节点的位置。
- 计算当前拖动节点与其他节点的相对位置,判断是否需要对齐。
- 如果需要对齐,则修改当前节点的位置,使其与参考节点对齐。
import { Graph } from '@antv/x6';
// 创建画布
const graph = new Graph({
container: document.getElementById('container'),
grid: true, // 显示网格辅助对齐
});
// 监听节点拖动事件
graph.on('node:moved', ({ node }) => {
// 获取拖拽节点的包围盒
const bbox = node.getBBox();
// 取中点位置坐标对齐
const center = {
x: bbox.x + bbox.width / 2,
y: bbox.y + bbox.height / 2,
};
// 获取所有其他节点
const otherNodes = graph.getNodes().filter((n) => n.id !== node.id);
// 对齐阈值,根据需要调整,表示当靠近最近的节点10px的时候触发自动对齐
const threshold = 10;
// 查找最近节点进行对齐
otherNodes.forEach((otherNode) => {
const otherBBox = otherNode.getBBox();
const otherCenter = {
x: otherBBox.x + otherBBox.width / 2,
y: otherBBox.y + otherBBox.height / 2,
};
// 水平对齐
if (Math.abs(center.x - otherCenter.x) < threshold) {
node.position(otherNode.position().x, bbox.y);
}
// 垂直对齐
if (Math.abs(center.y - otherCenter.y) < threshold) {
node.position(bbox.x, otherNode.position().y);
}
});
});
// 示例:添加节点到画布
graph.addNode({
x: 40,
y: 40,
width: 100,
height: 40,
attrs: {
body: {
fill: '#1890FF',
stroke: '#000000',
},
label: {
text: '节点',
fill: '#FFFFFF',
},
},
});
上述代码中主要依赖自定义事件来实现节点拖拽的监听
// move 代表 移动前会触发一次
// moving 代表 移动中会一直触发
// moved 代表 移动完后才会触发
graph.on('node:moved', ({ node }) => {})
获取完节点位置(getNodes
)后,在触发方法中可以使用 position
方法来动态改变节点的位置实现自动对齐