You need to enable JavaScript to run this app. 如何在mxgraph画布中禁止重复放置同一拖拽元素
优惠活动
大模型
产品
解决方案
定价
更多

如何在mxgraph画布中禁止重复放置同一拖拽元素

mxgraph禁止重复放置拖拽元素实现方案

核心实现逻辑如下:

  1. 新增Set集合存储已放置到画布的元素ID,用于放置前的重复校验
  2. 为拖拽生成的mxCell添加自定义属性shapeId,绑定对应拖拽源的DOM ID作为唯一标识
  3. 修改放置处理器逻辑,放置前先遍历画布中所有顶点,判断待放置的元素ID是否已存在,存在则直接终止放置操作

修改后的完整JS代码:

var graph = {};
// 存储已放置到画布的元素ID
const placedShapeIds = new Set();

function initCanvas() {
  graph = new mxGraph(document.getElementById('graph-wrapper'));
  graph.htmlLabels = true;
  graph.cellsEditable = false;

  graph.convertValueToString = function(cell) {
    return cell.value;
  }

  const createDropHandler = function (cells, allowSplit) {
    return function (graph, evt, target, x, y) {
      // 校验待放置元素是否已存在
      const targetShapeId = cells[0].shapeId;
      const allCells = graph.model.getDescendants(graph.model.getDefaultParent());
      const isDuplicate = allCells.some(cell => cell.vertex && cell.shapeId === targetShapeId);
      if (isDuplicate) return;

      const select = graph.importCells(cells, x, y, target);
      // 放置成功后记录元素ID
      placedShapeIds.add(targetShapeId);
      graph.setSelectionCells(select);
    };
  };

  const createDragPreview = function (width, height) {
    var elt = document.createElement('div');
    elt.style.border = '1px dashed black';
    elt.style.width = width + 'px';
    elt.style.height = height + 'px';
    return elt;
  };

  const createDragSource = function (elt, dropHandler, preview) {
    return mxUtils.makeDraggable(elt, graph, dropHandler, preview, 0, 0, graph.autoscroll, true, true);
  };

  const createItem = (id) => {
    const elt = document.getElementById(id);
    const width = elt.clientWidth;
    const height = elt.clientHeight;

    const cell = new mxCell('', new mxGeometry(0, 0, width, height), 'fillColor=none;strokeColor=none');
    cell.vertex = true;
    // 给cell绑定拖拽源的唯一ID
    cell.shapeId = id;
    graph.model.setValue(cell, elt);

    const cells = [cell];

    const bounds = new mxRectangle(0, 0, width, height);
    createDragSource(elt, createDropHandler(cells, true, false, bounds), createDragPreview(width, height), cells, bounds);
  };

  // 可选:监听元素删除事件,删除元素后允许重新拖拽放置
  graph.addListener(mxEvent.CELLS_REMOVED, function(sender, evt){
    const removedCells = evt.getProperty('cells');
    removedCells.forEach(cell => {
      if(cell.vertex && cell.shapeId){
        placedShapeIds.delete(cell.shapeId);
      }
    });
  });

  createItem("shape_1");
  createItem("shape_2");
  createItem("shape_3");
}

CSS和HTML代码无需修改,直接使用原有代码即可。修改后每个元素仅允许拖拽放置一次,若需要支持删除后重新放置,保留上述删除事件监听代码即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:39:02