Cytoscape JS - 通过从外部调色板拖放来创建节点

问题描述 投票:0回答:1

有没有一种方法可以通过从图形外部拖放某些东西来创建新节点,例如调色板或其他东西。 我认为没有这样的扩展,我发现的唯一一个是这个:https://github.com/ayushkr19/cytoscape.js-nodeadd,它已有 9 年历史,使用 jQuery。

如果没有扩展,我怎么可能使用事件监听器来处理这个问题?

谢谢。

javascript cytoscape.js
1个回答
0
投票

好的,我找到了方法,这是我的解决方案;)

参考

const graphRef = useRef<Core>()

UI 按钮

<div draggable="true">
    <button>Add toto node</button>
</div>

Cytoscape 包装器

<div onDrop={(e) => handleCreateNode(e)} onDragOver={(e) => e.preventDefault()}>
  <CytoscapeComponent
    cy={(cy) => (graphRef.current = cy)}
  />
</div>

和键,在正确的地方创建节点的函数

const handleCreateNode = (e: DragEvent<HTMLDivElement>) => {
  if (!graphRef.current) return;

  e.preventDefault();

  const pan = graphRef.current.pan();
  const zoom = graphRef.current.zoom();
  const x = e.nativeEvent.offsetX
  const y = e.nativeEvent.offsetY

  graphRef.current.add({
    data: { id: String(Math.random()), label: addType },
    position: {
      x: (x - pan.x) / zoom,
      y: (y - pan.y) / zoom,
    },
  });
};

这是一个 React 工作版本。

© www.soinside.com 2019 - 2024. All rights reserved.