JSFiddle - React, Tailwind, and code Playground
by Rajesh Danabal
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Network Graph with Clusters</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="networkCanvas"></canvas>
<script>
const canvas = document.getElementById("networkCanvas");
const ctx = canvas.getContext("2d");
function hexToRgba(hex, alpha = 1) {
hex = hex.replace(/^#/, "");
if (hex.length === 3) {
hex = hex.split("").map(char => char + char).join("");
}
const bigint = parseInt(hex, 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const numNodes = 100;
const numClusters = 5;
const clusterCenters = [];
const hullOffset = 30;
// Generate cluster centers
for (let i = 0; i < numClusters; i++) {
clusterCenters.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height
});
}
// Create nodes with clusters
const nodes = [];
for (let i = 0; i < numNodes; i++) {
const cluster = i % numClusters;
nodes.push({
id: i,
cluster,
x: clusterCenters[cluster].x + Math.random() * 100 - 50,
y: clusterCenters[cluster].y + Math.random() * 100 - 50
});
}
// Create links between same-cluster nodes
const links = [];
nodes.forEach((node, i) => {
for (let j = 0; j < 2; j++) {
const target = Math.floor(Math.random() * numNodes);
...