Code:
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>
// Sample data
const data = {
nodes: [
{id: '1', name: 'Node 1', color: 'red'},
{id: '2', name: 'Node 2', color: 'black'},
{id: '3', name: 'Node 3', color: 'green'}
],
links: [
{source: '1', target: '2'},
{source: '2', target: '3'}
]
};
// Dimensions
const width = 0.5 * window.innerWidth;
const height = 0.5 * window.innerHeight;
// Create SVG element
const svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "2px")
.style("border-radius", "5px")
.style("padding", "5px")
.style("position", "absolute")
;
// Create simulation
const simulation = d3.forceSimulation(data.nodes)
.force('link', d3.forceLink(data.links).id(d => d.id))
.force('charge', d3.forceManyBody().strength(-400))
.force('center', d3.forceCenter(width / 2, height / 2));
// Add links
const link = svg.append('g')
.attr('class', 'links')
.selectAll('line')
.data(data.links)
.enter().append('line')
.attr('class', 'link');
// Add nodes
const node = svg.append('g')
.attr('class', 'nodes')
.selectAll('circle')
.data(data.nodes)
.enter().append('circle')
.attr('class', 'node')
.attr('r', 10)
.attr('fill', d => d.color)
.call(drag(simulation));
// Add labels
node.append('title')
.text(d => d.name);
simulation.on('tick', () => {
link
.attr('x1', d => d.source.x)
.attr('y1', d => d.source.y)
.attr('x2', d => d.target.x)
.attr('y2', d => d.target.y);
node
.attr('cx', d => d.x)
.attr('cy', d => d.y);
});
// Drag function
function drag(simulation) {
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return d3.drag()
.on('start', dragstarted)
.on('drag', dragged)
.on('end', dragended);
}
</script>