[D3] Force + Drag + Zoom

by sunilbg

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>
<body>
    <div id="map"></div>
</body>

CSS

.node {
  stroke: #fff;
  stroke-width: 1.5px;
}

.node-active{
  stroke: #555;
  stroke-width: 1.5px;
}

.link {
  stroke: #555;
  stroke-opacity: .3;
}

.link-active {
  stroke-opacity: 1;
}

.overlay {
  fill: none;
  pointer-events: all;
}

#map{
    border: 2px #555 dashed;
    width:500px;
    height:400px;
}

JavaScript

var graph = {
	"nodes": [
		{"id": "1","name":"Ann"  ,"group": 1},
		{"id": "2","name":"Bill"  ,"group": 1},
		{"id": "3","name":"Charles"  ,"group": 1},
		{"id": "4","name":"Diane"  ,"group": 1},
		{"id": "5","name":"Went to gym this morning"  ,"group": 1},
],
"links": [
		{"source": "1", "target": "2", "value": 1, "name":"test"},
		{"source": "2", "target": "3", "value": 1, "name":"test"},
		{"source": "3", "target": "4", "value": 1, "name":"test"},
		{"source": "4", "target": "5", "value": 1, "name":"test"},
		{"source": "3", "target": "5", "value": 1, "name":"test"},
]
}

var margin = {top: -5, right: -5, bottom: -5, left: -5};
        var width = 500 - margin.left - margin.right,
	height = 400- margin.top - margin.bottom;

        var color = d3.scale.category20();
	
	var force = d3.layout.force()
            .charge(-200)
            .linkDistance(50)
            .size([width + margin.left + margin.right, height + margin.top + margin.bottom]);

        var zoom = d3.behavior.zoom()
            .scaleExtent([1, 10])
            .on("zoom", zoomed);

        var drag = d3.behavior.drag()
            .origin(function(d) { return d; })
            .on("dragstart", dragstarted)
            .on("drag", dragged)
            .on("dragend", dragended);


        var svg = d3.select("#map").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
            .call(zoom);

        var rect = svg.append("rect")
            .attr("width", width)
            .attr("height", height)
            .style("fill", "none")
            .style("pointer-events", "all");

        var container = svg.append("g");

//d3.json('http://blt909.free.fr/wd/map2.json', function(error, graph) {
                
                force
                    .nodes(graph.nodes)
                   ...