Код: Выделить всё
import Graph from "graphology";
import Sigma from "sigma";
// Create a new graph instance
const graph = new Graph();
// Add nodes and an edge to the graph
graph.addNode("1", { label: "Node 1", x: 0, y: 0, size: 10, color: "blue" });
graph.addNode("2", { label: "Node 2", x: 1, y: 1, size: 20, color: "red" });
graph.addEdge("1", "2", { size: 5, color: "purple" });
// Get the container element from the HTML
const container = document.getElementById("container");
if (!container) {
console.error("Container element not found. Make sure #container exists in the HTML.");
} else {
// Initialize Sigma renderer
const renderer = new Sigma(graph, container);
// Create a div to act as the info box
const infoBox = document.createElement("div");
infoBox.style.position = "absolute";
infoBox.style.border = "1px solid #ccc";
infoBox.style.backgroundColor = "#fff";
infoBox.style.padding = "10px";
infoBox.style.zIndex = "1000";
infoBox.style.display = "none"; // Initially hidden
document.body.appendChild(infoBox);
// Add event listener for node clicks
renderer.on("clickNode", (event) => {
const nodeId = event.node;
const nodeAttributes = graph.getNodeAttributes(nodeId);
// Populate the info box with node details
infoBox.innerHTML = `
Node Details
[b]${nodeAttributes.label}[/b]
This node has a size of ${nodeAttributes.size} and is colored ${nodeAttributes.color}.
Feel free to explore the graph!
`;
// Get the screen coordinates of the node
const nodeDisplayData = renderer.getNodeDisplayData(nodeId);
if (nodeDisplayData) {
// Offset the coordinates to position the info box correctly in the viewport
const containerRect = container.getBoundingClientRect();
const adjustedX = containerRect.left + nodeDisplayData.x - infoBox.offsetWidth / 2;
const adjustedY = containerRect.top + nodeDisplayData.y - infoBox.offsetHeight - 10; // Position above the node
// Set the info box position
infoBox.style.left = `${adjustedX}px`;
infoBox.style.top = `${adjustedY}px`;
infoBox.style.display = "block";
// Log the final coordinates of the text box to the console
console.log(`InfoBox Coordinates: X = ${adjustedX}, Y = ${adjustedY}`);
}
});
// Add event listener to hide the info box when clicking on the stage
renderer.on("clickStage", () => {
infoBox.style.display = "none";
});
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ma-js-node