Antv X6 - 拖拽到节点附近自动对齐


官网: X6·图编辑引擎


支持节点和边的操作,包括拖拽、对齐等。如果你想在拖动节点时自动进行水平或垂直对齐,你可以通过监听节点的拖动事件,并计算节点之间的相对位置来实现。

  1. 监听节点的 node:moved / node:dragging 事件,这个事件会在节点拖动时触发。
  2. 在事件处理函数中,获取所有节点的位置。
  3. 计算当前拖动节点与其他节点的相对位置,判断是否需要对齐。
  4. 如果需要对齐,则修改当前节点的位置,使其与参考节点对齐。
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 方法来动态改变节点的位置实现自动对齐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值