Adding cytoscape node at the location of mouse cursor

≯℡__Kan透↙ 提交于 2019-12-10 11:27:56

问题


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?


回答1:


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/




回答2:


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,
        },
    });
});



回答3:


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 },
    ]);
});


来源:https://stackoverflow.com/questions/19115940/adding-cytoscape-node-at-the-location-of-mouse-cursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!