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