Created
September 25, 2016 09:38
-
-
Save rsk2327/23622500eb512b5de90f6a916c836a40 to your computer and use it in GitHub Desktop.
Many-Body (forceManyBody)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Bar Chart</title> | |
<script type="text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> | |
<style type = "text/css"> | |
.active { | |
stroke: #000; | |
stroke-width: 2px; | |
} | |
.links line { | |
stroke: #aaa; | |
} | |
.nodes circle { | |
pointer-events: all; | |
stroke: none; | |
stroke-width: 40px; | |
} | |
</style> | |
</head> | |
<body> | |
<script> | |
var width = 1000, | |
height = 600; | |
var svg = d3.select("body").append("svg").attr("width",width) | |
.attr("height",height); | |
var nodeData = [{'x':100,'y':100,'r':10}, | |
{'x':200,'y':100,'r':10}, | |
{'x':50,'y':200,'r':10}, | |
{'x':350,'y':200,'r':10}, | |
{'x':100,'y':300,'r':10}, | |
{'x':300,'y':300,'r':10}]; | |
var attractForce = d3.forceManyBody().strength(200).distanceMax(400).distanceMin(60); | |
var repelForce = d3.forceManyBody().strength(-140).distanceMax(50).distanceMin(10); | |
var simulation = d3.forceSimulation(nodeData).alphaDecay(0.03).force("attractForce",attractForce).force("repelForce",repelForce); | |
var node = svg.selectAll("circle").data(nodeData) | |
.enter().append("circle") | |
.attr("r",function(d){ return d.r;}).attr("cx",function(d){ return d.x;}).attr("cy",function(d){ return d.y;}) | |
.attr("fill","black").attr("opacity",0.5) | |
.call(d3.drag() | |
.on("start",dragstarted) | |
.on("drag",dragged) | |
.on("end",dragended)); | |
function dragstarted(d) | |
{ | |
simulation.restart(); | |
simulation.alpha(1.0); | |
d.fx = d.x; | |
d.fy = d.y; | |
} | |
function dragged(d) | |
{ | |
d.fx = d3.event.x; | |
d.fy = d3.event.y; | |
} | |
function dragended(d) | |
{ | |
d.fx = null; | |
d.fy = null; | |
simulation.alphaTarget(0.1); | |
} | |
function ticked(){ | |
node.attr("cx", function(d){ return d.x;}) | |
.attr("cy", function(d){ return d.y;}) | |
} | |
simulation.on("tick",ticked); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment