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 {
display:block; /* required for firefox to give valid
height and width used values for getComputedStyle()
see https://bugzilla.mozilla.org/show_bug.cgi?id=874919
*/
border: solid 1px gray;
margin:1em;
height:calc(100% - 2em);
width: calc(100% - 2em);
}
div{
height: 100%;
}
JavaScript
var w = 400,
h = 400,
nodeCircles,
linkLines,
root;
/*** Create scales to handle zoom coordinates ***/
var xScale = d3.scale.linear()
.domain([0,w]);
var yScale = d3.scale.linear()
.domain([0,h]);
//ranges will be set later based on the size
//of the SVG
/*** 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 = xScale.invert(mouse[0]);
d.y = yScale.invert(mouse[1]);
tick();//re-position this node and any links
}
function dragended(d){
d3.select(this).classed("dragging", false);
force.resume();
}
var svg = d3.select(".intgraph").append("svg:svg")
.style("max-width", 2*w)
.style("max-height", 2*h);
var graph = svg.append("g")
...