Replies: 1 comment
-
To achieve the effect of a connecting line magnetizing when trying to connect two nodes on the canvas and when approaching the port in G6 5.x, you can utilize the built-in features of G6 to handle this interaction. Here's a general approach to implement this functionality:
Here's a basic example of how you might implement this: const graph = new G6.Graph({
container: 'mountNode',
width: 800,
height: 600,
modes: {
default: ['drag-node', 'create-edge'],
},
defaultNode: {
type: 'circle',
size: [50],
style: {
fill: '#9FD4FF',
stroke: '#5B8FF9',
},
ports: {
items: [
{ id: 'port1', x: 0, y: -25 },
{ id: 'port2', x: 25, y: 0 },
{ id: 'port3', x: 0, y: 25 },
{ id: 'port4', x: -25, y: 0 },
],
},
},
defaultEdge: {
style: {
stroke: '#F6BD16',
},
},
});
graph.on('edge:add', (evt) => {
const { edge } = evt;
const targetNode = graph.findById(edge.getTarget().getID());
const targetPorts = targetNode.getPorts();
const mousePos = graph.getPointByClient(evt.clientX, evt.clientY);
let minDistance = Infinity;
let closestPort = null;
targetPorts.forEach((port) => {
const portPos = port.getModel();
const distance = Math.sqrt(
Math.pow(portPos.x - mousePos.x, 2) + Math.pow(portPos.y - mousePos.y, 2)
);
if (distance < minDistance) {
minDistance = distance;
closestPort = port;
}
});
if (closestPort) {
edge.update({
target: closestPort.getID(),
});
}
}); Explanation:
This example provides a basic framework. You may need to adjust the logic to fit your specific requirements, such as handling different node shapes or customizing the snapping behavior. If you have any further questions or need more detailed guidance, feel free to ask! 🪧 TipsFor further assistance, please describe your question in the comments and @petercat-assistant to start a conversation with me. |
Beta Was this translation helpful? Give feedback.
-
How to make the connecting line magnetize when trying to connect two nodes on the canvas and when approaching the port in G6 5.x
Beta Was this translation helpful? Give feedback.
All reactions