JSFiddle - React, Tailwind, and code Playground
HTML
<div id="main">
<div class="intgraph" />
</div>
CSS
circle.node {
stroke: #555;
stroke-width: .5px;
}
line.link {
fill: none;
stroke: #9ecae1;
stroke-width: 1.5px;
}
svg {
border: solid 1px gray;
}
JavaScript
var w = 400,
h = 400,
nodeCircles,
linkLines,
root;
var scaleFactor = 1;
var translation = [0,0];
/*** Configure Force Layout ***/
var force = d3.layout.force()
.on("tick", tick)
.charge(function (d) {
return d._children ? -d.size / 100 : -50;
})
.linkDistance(function (d) {
return d.target._children ? 80 : 30;
})
.friction(0.90) //slow down by 10% each tick
.size([w, h]);
/*** Configure zoom behaviour ***/
var zoomer = d3.behavior.zoom()
.scaleExtent([0.1,10])
//allow 10 times zoom in or out
.on("zoom", zoom);
//define the event handler function
function zoom() {
console.log("zoom", d3.event.translate, d3.event.scale);
scaleFactor = d3.event.scale;
translation = d3.event.translate;
tick(); //update positions
}
/*** Configure drag behaviour ***/
var drag = d3.behavior.drag()
.origin(function(d) { return d; }) //center of circle
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
function dragstarted(d){
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
force.stop(); //stop ticks while dragging
}
function dragged(d){
if (d.fixed) return; //root is fixed
//get mouse coordinates relative to the visualization
//coordinate system:
var mouse = d3.mouse(vis.node());
d.x = (mouse[0] - translation[0])/scaleFactor;
d.y = (mouse[1] - translation[1])/scaleFactor;
tick();//re-position this node and any links
}
function dragended(d){
d3.select(this).classed("dragging", false);
force.resume();
}
/** Initialize SVG ***/
var graph = d3.select(".intgraph").append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("class", "graph")
.call(zoomer); //Attach zoom behaviour.
// Add a transparent background rectangle to catch
// mouse events for the zoom...