Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

cytoscape.js - Is there a way to tell if a Cystoscape node is at a certain coordinates using Javascript?

I have an application where the user can create graphs using Cytoscape JS. To add a node the user clicks on the Cytoscape container and a node is added at the click position. Recently, I have added implemented my own snap-to-grid methods, and I am wondering if there is any way I can check if a node already exists at certain coordinates, as to not allow the user to create overlapping nodes. I've searched and searched through the Cytoscape JS documentation and haven't had any luck finding anything useful. Future thanks for any assistance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using event listeners, you should implement them according to your goals. Clicking on nodes, edges or the canvas can all implement their own logic within the event listener (cy.on()):

// unbind click events first
cy.off('click');

// click event for nodes
cy.on('click', 'node', function(evt){
   ...
});

// click event for edges
cy.on('click', 'edge', function(evt){
   ...
});

// click event for the canvas
cy.on('tap', function(event){
  if( event.target === cy ){
    ...
  }
});

With this, you can add nodes to the canvas, skip adding them on nodes and edges or do some other stuff like an alert for the user with some information about why they should choose another location.

If you want to manually check if a location is empty, you can do it naively like this:

cy.nodes().each(function(node) {
    // yourPosition should be look like this: { x: x-pos, y: y-pos }
    // where x-/y-pos are the grid positions x and y coordinates
    if(node.position() == yourPosition) { 
        // do something 
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...