Adding cytoscape node at the location of mouse cursor
Asked Answered
F

3

5

I want to add a cytoscape node at the location of mouse arrow, on a click event on the canvas.

How can I do this?

My approach: (not working so well)

I am able to create a node on a click but I am not able to make sure the position of the created node is at the place where I have clicked. Using something like this:

$("#cy").click(function(event){

    pos = getMousePosition(this, event)

    cy.add([
      { group: "nodes", data: { id: "testid" }, position: pos },
    ]);
});

I have not been able to define getMousePosition() correctly. How should I define this function to get the node rendered at the right position irrespective of the location of the cytoscape canvas?

Formulary answered 1/10, 2013 at 12:17 Comment(0)
S
4

The mouse works with rendered coordinates on the screen. If you would like to add a node at a specific rendered position, it would be easiest to specify the new node position in rendered coordinates, e.g.:

cy.add([
  { group: "nodes", data: { id: "testid" }, renderedPosition: rpos } // , ...
]);

It then becomes trivial to pass the rendered mouse position (relative to the cy.js div), e.g. http://api.jquery.com/position/

Screed answered 10/10, 2013 at 14:16 Comment(3)
Perfect it works. "renderedPosition" parameter is the key. But I do not understand what "position" parameter was doing then?Formulary
when you set the node's rendered position, does its model position also get set/updated automatically?Jeromejeromy
Everything is consistent regardless of which way position is set. Otherwise there would be contradictionsScreed
F
3

In cytoscape.js 3.2, there are convenience functions for this:

cy.on("tap", function(e) {
    cy.add([{
        group: "nodes",
        id: "testid",
        renderedPosition: {
            x: e.renderedPosition.x,
            y: e.renderedPosition.y,
        },
    });
});

This ends up being equivalent to (assuming you've set container: $("#cy-container")):

cy.on("tap", function(e) {
    let canvas = $("#cy-container").find("canvas").get(0);
    cy.add([{
        group: "nodes",
        id: "testid",
        renderedPosition: {
            x: e.originalEvent.pageX - $(canvas).offset().left,
            y: e.originalEvent.pageY - $(canvas).offset().top,
        },
    });
});
Fosterfosterage answered 15/11, 2018 at 22:53 Comment(0)
W
0

It was not clear to me how to use the jQuery's position funciton in order to get the mouse coordinates, as the @maxfranz suggested.

The code I use is:

$("#cy").click(function(event) {
    var pos = {x: event.offsetX, y: event.offsetY};
    cy.add([
        { group: "nodes", data: { id: "testid" }, renderedPosition: pos },
    ]);
});
Woodall answered 8/2, 2017 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.