You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在mxGraph连接时获取mxConnectionConstraint定义的连接点名称

获取mxGraph连接对应的自定义连接点名称

解决方案

当连接通过自定义mxConnectionConstraint建立后,可通过两种方式获取连接点名称:

1. 监听连接创建事件

利用mxEvent.CONNECT事件,在连接完成后直接从边缘(edge)的几何信息中提取约束名称:

// 监听连接创建事件
graph.addListener(mxEvent.CONNECT, function(sender, evt) {
  const edge = evt.getProperty('edge');
  const geometry = edge.getGeometry();

  // 获取源节点的连接点名称
  if (geometry.sourceConstraint) {
    console.log('源连接点:', geometry.sourceConstraint.name);
  }
  // 获取目标节点的连接点名称
  if (geometry.targetConstraint) {
    console.log('目标连接点:', geometry.targetConstraint.name);
  }
});

2. 重写mxGraph的connect方法

在重写方法中直接获取传入的约束参数,还可将约束信息持久化到边缘的几何对象中:

// 保存原connect方法
const originalConnect = graph.connect;

// 重写connect方法
graph.connect = function(edge, source, target, sourceConstraint, targetConstraint, dx, dy) {
  // 调用原方法完成连接
  originalConnect.apply(this, arguments);

  // 直接获取连接点名称
  if (sourceConstraint) {
    console.log('源连接点名称:', sourceConstraint.name);
  }
  if (targetConstraint) {
    console.log('目标连接点名称:', targetConstraint.name);
  }

  // 可选:将约束信息存入edge的geometry,方便后续获取
  const geo = edge.getGeometry();
  geo.sourceConstraint = sourceConstraint;
  geo.targetConstraint = targetConstraint;
  this.model.setGeometry(edge, geo);
};

注意事项

  • 确保自定义的mxConnectionConstraint正确传入了名称参数(如示例中的'top'、'bottom')
  • 若之前重写connect方法未成功,检查是否正确调用了原方法,以及是否正确接收sourceConstraint和targetConstraint参数

内容的提问来源于stack exchange,提问作者EaBengaluru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:20:35