Create a social network graph analysis tool.
- User
Create a social network graph analysis tool.
Assistant
Create a social network graph analysis tool.
The user wants a social network graph analysis tool. This is a data visualization/analysis tool, so I need to create something interactive and visually appealing.
Let me think about what features a social network graph analysis tool should have:
Design approach:
Color scheme:
Let me create this comprehensive tool:
This will be a single HTML file with all the functionality.
I'll create an interactive social network visualization tool with force-directed layout, community detection, centrality metrics, and dynamic visual effects.
Key Features:
Force-Directed Layout - Nodes naturally spread out and organize based on connections
Community Detection - Automatically identifies clusters and color-codes them
Centrality Metrics - Calculates degree, closeness, and visualizes importance
Shortest Path Finding - Select two nodes to find the shortest connection path (highlighted in orange)
Interactive Controls:
Visual Effects:
Statistics Panel - Real-time network metrics (node count, edge count, average degree, density)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Social Network Graph Analysis</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #0a0e17;
color: #e0e6ed;
overflow: hidden;
height: 100vh;
}
#canvas {
position: fixed;
top: 0;
left: 0;
z-index: 1;
}
.sidebar {
position: fixed;
right: 0;
top: 0;
width: 320px;
height: 100vh;
background: linear-gradient(180deg, #12182a 0%, #0d1220 100%);
border-left: 1px solid #2a3a5a;
z-index: 10;
padding: 20px;
overflow-y: auto;
box-shadow: -5px 0 30px rgba(0,0,0,0.5);
}
.sidebar h1 {
font-size: 1.4em;
margin-bottom: 8px;
background: linear-gradient(135deg, #00d4ff, #7b2dff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.sidebar .subtitle {
font-size: 0.8em;
color: #6b7c9a;
margin-bottom: 20px;
}
.panel {
background: rgba(30, 45, 80, 0.4);
border-radius: 12px;
padding: 15px;
margin-bottom: 15px;
border: 1px solid rgba(100, 140, 200, 0.2);
}
.panel h3 {
font-size: 0.9em;
color: #8ba4c7;
margin-bottom: 12px;
text-transform: uppercase;
letter-spacing: 1px;
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.stat-item {
background: rgba(0, 180, 255, 0.08);
padding: 12px;
border-radius: 8px;
text-align: center;
transition: all 0.3s ease;
}
.stat-item:hover {
background: rgba(0, 180, 255, 0.15);
transform: translateY(-2px);
}
.stat-value {
font-size: 1.6em;
font-weight: bold;
color: #00d4ff;
}
.stat-label {
font-size: 0.7em;
color: #6b7c9a;
margin-top: 4px;
}
.btn {
width: 100%;
padding: 12px;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 0.85em;
font-weight: 600;
transition: all 0.3s ease;
margin-bottom: 8px;
}
.btn-primary {
background: linear-gradient(135deg, #00b4d8, #0077b6);
color: white;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(0, 180, 216, 0.4);
}
.btn-secondary {
background: rgba(100, 120, 160, 0.2);
color: #a0b4cc;
border: 1px solid rgba(100, 140, 200, 0.3);
}
.btn-secondary:hover {
background: rgba(100, 120, 160, 0.35);
}
.btn-danger {
background: rgba(255, 80, 100, 0.2);
color: #ff6b7a;
border: 1px solid rgba(255, 80, 100, 0.3);
}
.btn-danger:hover {
background: rgba(255, 80, 100, 0.35);
}
.node-list {
max-height: 150px;
overflow-y: auto;
}
.node-item {
display: flex;
align-items: center;
padding: 8px;
border-radius: 6px;
margin-bottom: 4px;
cursor: pointer;
transition: all 0.2s ease;
}
.node-item:hover {
background: rgba(100, 140, 200, 0.15);
}
.node-item.selected {
background: rgba(0, 180, 255, 0.2);
border: 1px solid rgba(0, 180, 255, 0.4);
}
.node-color {
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 10px;
}
.node-name {
flex: 1;
font-size: 0.85em;
}
.node-degree {
font-size: 0.75em;
color: #6b7c9a;
}
.input-group {
margin-bottom: 10px;
}
.input-group input {
width: 100%;
padding: 10px 12px;
border: 1px solid rgba(100, 140, 200, 0.3);
border-radius: 8px;
background: rgba(20, 35, 60, 0.6);
color: #e0e6ed;
font-size: 0.9em;
}
.input-group input:focus {
outline: none;
border-color: #00d4ff;
box-shadow: 0 0 10px rgba(0, 212, 255, 0.2);
}
.centrality-bar {
height: 6px;
background: rgba(100, 140, 200, 0.2);
border-radius: 3px;
margin-top: 6px;
overflow: hidden;
}
.centrality-fill {
height: 100%;
border-radius: 3px;
transition: width 0.5s ease;
}
.tooltip {
position: fixed;
background: rgba(20, 35, 60, 0.95);
border: 1px solid rgba(100, 140, 200, 0.4);
border-radius: 8px;
padding: 12px;
font-size: 0.8em;
pointer-events: none;
z-index: 100;
opacity: 0;
transition: opacity 0.2s ease;
max-width: 200px;
}
.tooltip.visible {
opacity: 1;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.legend-item {
display: flex;
align-items: center;
font-size: 0.75em;
}
.legend-color {
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 5px;
}
.path-info {
background: rgba(123, 45, 255, 0.15);
border: 1px solid rgba(123, 45, 255, 0.3);
border-radius: 8px;
padding: 10px;
margin-top: 10px;
font-size: 0.8em;
}
.path-nodes {
color: #b794ff;
margin-top: 5px;
}
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: rgba(30, 45, 80, 0.3);
}
::-webkit-scrollbar-thumb {
background: rgba(100, 140, 200, 0.4);
border-radius: 3px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div class="sidebar">
<h1>Network Graph Analysis</h1>
<p class="subtitle">Interactive Social Network Visualization</p>
<div class="panel">
<h3>Network Statistics</h3>
<div class="stats-grid">
<div class="stat-item">
<div class="stat-value" id="nodeCount">0</div>
<div class="stat-label">Nodes</div>
</div>
<div class="stat-item">
<div class="stat-value" id="edgeCount">0</div>
<div class="stat-label">Edges</div>
</div>
<div class="stat-item">
<div class="stat-value" id="avgDegree">0</div>
<div class="stat-label">Avg Degree</div>
</div>
<div class="stat-item">
<div class="stat-value" id="density">0</div>
<div class="stat-label">Density</div>
</div>
</div>
</div>
<div class="panel">
<h3>Add Node</h3>
<div class="input-group">
<input type="text" id="nodeName" placeholder="Node name...">
</div>
<button class="btn btn-primary" onclick="addNode()">Add Node</button>
<button class="btn btn-secondary" onclick="addRandomNodes(5)">Add 5 Random</button>
</div>
<div class="panel">
<h3>Selection</h3>
<p style="font-size: 0.8em; color: #6b7c9a; margin-bottom: 10px;">
Click nodes to select. Select 2 nodes to:
</p>
<div id="selectedNodes" style="font-size: 0.85em; min-height: 24px;"></div>
<button class="btn btn-primary" onclick="connectSelected()">Connect Selected</button>
<button class="btn btn-secondary" onclick="findShortestPath()">Find Shortest Path</button>
<div id="pathResult"></div>
</div>
<div class="panel">
<h3>Actions</h3>
<button class="btn btn-secondary" onclick="detectCommunities()">Detect Communities</button>
<button class="btn btn-secondary" onclick="generateSampleNetwork()">Generate Sample Network</button>
<button class="btn btn-danger" onclick="clearSelection()">Clear Selection</button>
<button class="btn btn-danger" onclick="deleteSelected()">Delete Selected</button>
<button class="btn btn-danger" onclick="clearAll()">Clear All</button>
</div>
<div class="panel">
<h3>Top Nodes by Centrality</h3>
<div id="topNodes" class="node-list"></div>
</div>
<div class="panel">
<h3>Community Legend</h3>
<div id="communityLegend" class="legend"></div>
</div>
</div>
<div class="tooltip" id="tooltip"></div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const tooltip = document.getElementById('tooltip');
let width, height;
let nodes = [];
let edges = [];
let selectedNodes = [];
let highlightedPath = [];
let particles = [];
let communities = [];
let communityColors = [];
const communityPalette = [
'#00d4ff', '#7b2dff', '#ff6b9d', '#00ff88',
'#ffaa00', '#ff5555', '#55ffff', '#ff55ff',
'#88ff00', '#ff8800'
];
function resize() {
width = window.innerWidth - 320;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
}
class Node {
constructor(id, name, x, y) {
this.id = id;
this.name = name;
this.x = x || Math.random() * (width - 100) + 50;
this.y = y || Math.random() * (height - 100) + 50;
this.vx = 0;
this.vy = 0;
this.radius = 20;
this.color = '#00d4ff';
this.community = 0;
this.degree = 0;
this.betweenness = 0;
this.closeness = 0;
this.pulsePhase = Math.random() * Math.PI * 2;
}
}
class Edge {
constructor(source, target) {
this.source = source;
this.target = target;
this.weight = 1;
}
}
class Particle {
constructor(edge) {
this.edge = edge;
this.t = Math.random();
this.speed = 0.005 + Math.random() * 0.01;
this.size = 2 + Math.random() * 2;
}
update() {
this.t += this.speed;
if (this.t > 1) this.t = 0;
}
draw() {
const source = nodes.find(n => n.id === this.edge.source);
const target = nodes.find(n => n.id === this.edge.target);
if (!source || !target) return;
const x = source.x + (target.x - source.x) * this.t;
const y = source.y + (target.y - source.y) * this.t;
ctx.beginPath();
ctx.arc(x, y, this.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${0.6 + Math.sin(this.t * Math.PI) * 0.4})`;
ctx.fill();
}
}
function init() {
resize();
generateSampleNetwork();
animate();
}
function generateSampleNetwork() {
nodes = [];
edges = [];
selectedNodes = [];
highlightedPath = [];
particles = [];
const names = ['Alice', 'Bob', 'Carol', 'David', 'Eve', 'Frank', 'Grace', 'Henry', 'Ivy', 'Jack', 'Kate', 'Leo', 'Mia', 'Noah', 'Olivia'];
for (let i = 0; i < 15; i++) {
const angle = (i / 15) * Math.PI * 2;
const r = Math.min(width, height) * 0.3;
nodes.push(new Node(i, names[i], width/2 + Math.cos(angle) * r, height/2 + Math.sin(angle) * r));
}
const connections = [
[0,1],[0,2],[0,3],[1,2],[1,4],[2,5],[3,6],[3,7],
[4,5],[4,8],[5,9],[6,7],[7,10],[8,9],[8,11],[9,12],
[10,13],[11,12],[12,13],[13,14],[0,8],[2,10],[5,13]
];
connections.forEach(([s, t]) => {
if (s < nodes.length && t < nodes.length) {
edges.push(new Edge(s, t));
}
});
for (let i = 0; i < edges.length * 2; i++) {
particles.push(new Particle(edges[i % edges.length]));
}
detectCommunities();
updateStats();
}
function addNode() {
const input = document.getElementById('nodeName');
const name = input.value.trim() || `Node ${nodes.length + 1}`;
const node = new Node(nodes.length, name, width/2 + (Math.random()-0.5)*200, height/2 + (Math.random()-0.5)*200);
nodes.push(node);
input.value = '';
updateStats();
detectCommunities();
}
function addRandomNodes(count) {
for (let i = 0; i < count; i++) {
const name = `User${nodes.length + 1}`;
const node = new Node(nodes.length, name);
nodes.push(node);
if (nodes.length > 1) {
const randomNode = nodes[Math.floor(Math.random() * (nodes.length - 1))];
edges.push(new Edge(node.id, randomNode.id));
particles.push(new Particle(edges[edges.length - 1]));
particles.push(new Particle(edges[edges.length - 1]));
}
}
updateStats();
detectCommunities();
}
function connectSelected() {
if (selectedNodes.length !== 2) return;
const exists = edges.some(e =>
(e.source === selectedNodes[0].id && e.target === selectedNodes[1].id) ||
(e.source === selectedNodes[1].id && e.target === selectedNodes[0].id)
);
if (!exists) {
edges.push(new Edge(selectedNodes[0].id, selectedNodes[1].id));
particles.push(new Particle(edges[edges.length - 1]));
particles.push(new Particle(edges[edges.length - 1]));
updateStats();
detectCommunities();
}
}
function clearSelection() {
selectedNodes = [];
highlightedPath = [];
updateSelectedDisplay();
document.getElementById('pathResult').innerHTML = '';
}
function deleteSelected() {
selectedNodes.forEach(node => {
edges = edges.filter(e => e.source !== node.id && e.target !== node.id);
nodes = nodes.filter(n => n.id !== node.id);
});
particles = particles.filter(p => {
const edge = p.edge;
return nodes.find(n => n.id === edge.source) && nodes.find(n => n.id === edge.target);
});
clearSelection();
updateStats();
detectCommunities();
}
function clearAll() {
nodes = [];
edges = [];
particles = [];
clearSelection();
updateStats();
document.getElementById('communityLegend').innerHTML = '';
document.getElementById('topNodes').innerHTML = '';
}
function detectCommunities() {
if (nodes.length === 0) return;
const n = nodes.length;
const adjacency = Array(n).fill(null).map(() => Array(n).fill(0));
edges.forEach(e => {
adjacency[e.source][e.target] = 1;
adjacency[e.target][e.source] = 1;
});
const communityIds = Array(n).fill(0);
let maxCommunity = 0;
nodes.forEach((node, i) => {
let bestCommunity = 0;
let bestScore = -Infinity;
for (let c = 0; c <= maxCommunity + 1; c++) {
let score = 0;
nodes.forEach((other, j) => {
if (communityIds[j] === c && adjacency[i][j]) {
score++;
}
});
if (score > bestScore) {
bestScore = score;
bestCommunity = c;
}
}
communityIds[i] = bestCommunity;
if (bestCommunity > maxCommunity) maxCommunity = bestCommunity;
});
communities = [...new Set(communityIds)].sort((a, b) => a - b);
communityColors = communities.map(c => communityPalette[c % communityPalette.length]);
nodes.forEach((node, i) => {
node.community = communityIds[i];
node.color = communityColors[communities.indexOf(communityIds[i])] || communityPalette[0];
});
calculateCentralities();
updateLegend();
updateTopNodes();
}
function calculateCentralities() {
const n = nodes.length;
if (n === 0) return;
const adjacency = {};
nodes.forEach(node => adjacency[node.id] = new Set());
edges.forEach(e => {
adjacency[e.source].add(e.target);
adjacency[e.target].add(e.source);
});
nodes.forEach(node => {
node.degree = adjacency[node.id].size;
node.radius = 15 + node.degree * 3;
});
nodes.forEach(node => {
const distances = {};
const queue = [node.id];
distances[node.id] = 0;
while (queue.length > 0) {
const current = queue.shift();
adjacency[current].forEach(neighbor => {
if (distances[neighbor] === undefined) {
distances[neighbor] = distances[current] + 1;
queue.push(neighbor);
}
});
}
const totalDist = Object.values(distances).reduce((a, b) => a + b, 0);
const reachable = Object.keys(distances).length - 1;
node.closeness = reachable > 0 ? (reachable / totalDist) : 0;
});
let totalBetweenness = 0;
nodes.forEach(node => {
node.betweenness = Math.random() * node.degree;
totalBetweenness += node.betweenness;
});
nodes.forEach(node => {
node.betweenness /= Math.max(totalBetweenness, 1);
});
}
function findShortestPath() {
if (selectedNodes.length !== 2) return;
const start = selectedNodes[0].id;
const end = selectedNodes[1].id;
const adjacency = {};
nodes.forEach(node => adjacency[node.id] = new Set());
edges.forEach(e => {
adjacency[e.source].add(e.target);
adjacency[e.target].add(e.source);
});
const queue = [[start]];
const visited = new Set([start]);
while (queue.length > 0) {
const path = queue.shift();
const current = path[path.length - 1];
if (current === end) {
highlightedPath = path;
const pathNames = path.map(id => nodes.find(n => n.id === id).name).join(' → ');
document.getElementById('pathResult').innerHTML = `
<div class="path-info">
<strong>Shortest Path Found</strong>
<div class="path-nodes">${pathNames}</div>
<div style="color: #8ba4c7; margin-top: 5px;">Distance: ${path.length - 1} hops</div>
</div>
`;
return;
}
adjacency[current].forEach(neighbor => {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push([...path, neighbor]);
}
});
}
document.getElementById('pathResult').innerHTML = `
<div class="path-info" style="background: rgba(255,80,100,0.15); border-color: rgba(255,80,100,0.3);">
<strong style="color: #ff6b7a;">No Path Found</strong>
<div style="color: #8ba4c7;">These nodes are not connected</div>
</div>
`;
highlightedPath = [];
}
function updateStats() {
document.getElementById('nodeCount').textContent = nodes.length;
document.getElementById('edgeCount').textContent = edges.length;
const avgDegree = nodes.length > 0 ?
(edges.length * 2 / nodes.length).toFixed(1) : 0;
document.getElementById('avgDegree').textContent = avgDegree;
const maxEdges = nodes.length * (nodes.length - 1) / 2;
const density = maxEdges > 0 ? (edges.length / maxEdges).toFixed(2) : 0;
document.getElementById('density').textContent = density;
}
function updateLegend() {
const legend = document.getElementById('communityLegend');
legend.innerHTML = communities.map((c, i) => `
<div class="legend-item">
<div class="legend-color" style="background: ${communityColors[i]}"></div>
Community ${c + 1}
</div>
`).join('');
}
function updateTopNodes() {
const sorted = [...nodes].sort((a, b) => b.degree - a.degree).slice(0, 5);
const maxDegree = Math.max(...sorted.map(n => n.degree), 1);
document.getElementById('topNodes').innerHTML = sorted.map(node => `
<div class="node-item" onclick="selectNodeById(${node.id})">
<div class="node-color" style="background: ${node.color}"></div>
<span class="node-name">${node.name}</span>
<span class="node-degree">${node.degree}</span>
</div>
<div class="centrality-bar">
<div class="centrality-fill" style="width: ${(node.degree/maxDegree)*100}%; background: ${node.color}"></div>
</div>
`).join('');
}
function selectNodeById(id) {
const node = nodes.find(n => n.id === id);
if (node) {
const index = selectedNodes.findIndex(n => n.id === id);
if (index >= 0) {
selectedNodes.splice(index, 1);
} else {
if (selectedNodes.length >= 2) selectedNodes.shift();
selectedNodes.push(node);
}
updateSelectedDisplay();
}
}
function updateSelectedDisplay() {
const display = document.getElementById('selectedNodes');
if (selectedNodes.length === 0) {
display.innerHTML = '<span style="color: #6b7c9a;">No nodes selected</span>';
} else {
display.innerHTML = selectedNodes.map(n =>
`<span style="color: ${n.color}">${n.name}</span>`
).join(' → ');
}
}
function applyForces() {
const k = 0.01;
const repulsion = 5000;
const centerK = 0.001;
nodes.forEach(node => {
node.vx = 0;
node.vy = 0;
});
for (let i = 0; i < nodes.length; i++) {
for (let j = i + 1; j < nodes.length; j++) {
const dx = nodes[j].x - nodes[i].x;
const dy = nodes[j].y - nodes[i].y;
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
const force = repulsion / (dist * dist);
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
nodes[i].vx -= fx;
nodes[i].vy -= fy;
nodes[j].vx += fx;
nodes[j].vy += fy;
}
}
edges.forEach(edge => {
const source = nodes.find(n => n.id === edge.source);
const target = nodes.find(n => n.id === edge.target);
if (!source || !target) return;
const dx = target.x - source.x;
const dy = target.y - source.y;
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
const force = (dist - 100) * k;
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
source.vx += fx;
source.vy += fy;
target.vx -= fx;
target.vy -= fy;
});
nodes.forEach(node => {
node.vx += (width/2 - node.x) * centerK;
node.vy += (height/2 - node.y) * centerK;
node.x += node.vx;
node.y += node.vy;
node.x = Math.max(node.radius, Math.min(width - node.radius, node.x));
node.y = Math.max(node.radius, Math.min(height - node.radius, node.y));
});
}
function draw() {
ctx.fillStyle = '#0a0e17';
ctx.fillRect(0, 0, width, height);
const gradient = ctx.createRadialGradient(width/2, height/2, 0, width/2, height/2, Math.max(width, height)/2);
gradient.addColorStop(0, 'rgba(0, 50, 80, 0.3)');
gradient.addColorStop(1, 'rgba(10, 14, 23, 0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = 'rgba(40, 60, 100, 0.1)';
ctx.lineWidth = 1;
for (let i = 0; i < width; i += 50) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, height);
ctx.stroke();
}
for (let i = 0; i < height; i += 50) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(width, i);
ctx.stroke();
}
edges.forEach(edge => {
const source = nodes.find(n => n.id === edge.source);
const target = nodes.find(n => n.id === edge.target);
if (!source || !target) return;
const isInPath = highlightedPath.length > 0 &&
highlightedPath.includes(source.id) &&
highlightedPath.includes(target.id) &&
Math.abs(highlightedPath.indexOf(source.id) - highlightedPath.indexOf(target.id)) === 1;
ctx.beginPath();
ctx.moveTo(source.x, source.y);
ctx.lineTo(target.x, target.y);
if (isInPath) {
ctx.strokeStyle = '#ffaa00';
ctx.lineWidth = 4;
ctx.shadowColor = '#ffaa00';
ctx.shadowBlur = 15;
} else {
const alpha = 0.3 + (source.degree + target.degree) * 0.02;
ctx.strokeStyle = `rgba(100, 140, 200, ${Math.min(alpha, 0.6)})`;
ctx.lineWidth = 1.5;
ctx.shadowBlur = 0;
}
ctx.stroke();
ctx.shadowBlur = 0;
});
particles.forEach(p => {
p.update();
p.draw();
});
nodes.forEach(node => {
const isSelected = selectedNodes.includes(node);
const pulse = Math.sin(node.pulsePhase) * 0.15 + 1;
node.pulsePhase += 0.03;
if (isSelected) {
ctx.beginPath();
ctx.arc(node.x, node.y, node.radius * pulse + 8, 0, Math.PI * 2);
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 2;
ctx.stroke();
}
ctx.beginPath();
ctx.arc(node.x, node.y, node.radius * pulse, 0, Math.PI * 2);
const grad = ctx.createRadialGradient(
node.x - node.radius * 0.3,
node.y - node.radius * 0.3,
0,
node.x, node.y, node.radius
);
grad.addColorStop(0, lightenColor(node.color, 40));
grad.addColorStop(0.7, node.color);
grad.addColorStop(1, darkenColor(node.color, 30));
ctx.fillStyle = grad;
ctx.shadowColor = node.color;
ctx.shadowBlur = isSelected ? 25 : 15;
ctx.fill();
ctx.shadowBlur = 0;
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 11px Segoe UI';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(node.name, node.x, node.y);
});
}
function lightenColor(color, amount) {
const hex = color.replace('#', '');
const r = Math.min(255, parseInt(hex.substr(0, 2), 16) + amount);
const g = Math.min(255, parseInt(hex.substr(2, 2), 16) + amount);
const b = Math.min(255, parseInt(hex.substr(4, 2), 16) + amount);
return `rgb(${r},${g},${b})`;
}
function darkenColor(color, amount) {
const hex = color.replace('#', '');
const r = Math.max(0, parseInt(hex.substr(0, 2), 16) - amount);
const g = Math.max(0, parseInt(hex.substr(2, 2), 16) - amount);
const b = Math.max(0, parseInt(hex.substr(4, 2), 16) - amount);
return `rgb(${r},${g},${b})`;
}
function animate() {
applyForces();
draw();
requestAnimationFrame(animate);
}
let draggedNode = null;
let hoveredNode = null;
canvas.addEventListener('mousedown', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
for (let i = nodes.length - 1; i >= 0; i--) {
const node = nodes[i];
const dx = x - node.x;
const dy = y - node.y;
if (dx * dx + dy * dy < node.radius * node.radius) {
draggedNode = node;
return;
}
}
});
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
if (draggedNode) {
draggedNode.x = x;
draggedNode.y = y;
return;
}
hoveredNode = null;
for (let i = nodes.length - 1; i >= 0; i--) {
const node = nodes[i];
const dx = x - node.x;
const dy = y - node.y;
if (dx * dx + dy * dy < node.radius * node.radius) {
hoveredNode = node;
break;
}
}
if (hoveredNode) {
tooltip.innerHTML = `
<strong style="color: ${hoveredNode.color}">${hoveredNode.name}</strong><br>
<span style="color: #8ba4c7">Degree: ${hoveredNode.degree}</span><br>
<span style="color: #8ba4c7">Closeness: ${hoveredNode.closeness.toFixed(3)}</span><br>
<span style="color: #8ba4c7">Community: ${hoveredNode.community + 1}</span>
`;
tooltip.style.left = (e.clientX + 15) + 'px';
tooltip.style.top = (e.clientY + 15) + 'px';
tooltip.classList.add('visible');
canvas.style.cursor = 'pointer';
} else {
tooltip.classList.remove('visible');
canvas.style.cursor = 'default';
}
});
canvas.addEventListener('mouseup', () => {
draggedNode = null;
});
canvas.addEventListener('click', (e) => {
if (draggedNode) return;
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
for (let i = nodes.length - 1; i >= 0; i--) {
const node = nodes[i];
const dx = x - node.x;
const dy = y - node.y;
if (dx * dx + dy * dy < node.radius * node.radius) {
selectNodeById(node.id);
return;
}
}
});
window.addEventListener('resize', resize);
init();
</script>
</body>
</html>