Skip to content

Instantly share code, notes, and snippets.

@tiptopcoder
Last active May 23, 2018 15:57
Show Gist options
  • Save tiptopcoder/b437cad888a4ffde174e57c304bdee0c to your computer and use it in GitHub Desktop.
Save tiptopcoder/b437cad888a4ffde174e57c304bdee0c to your computer and use it in GitHub Desktop.
fresh block
license: mit
<!-- <!DOCTYPE html> -->
<meta charset="utf-8">
<head>
<title>Force layout (foci)</title>
</head>
<style>
</style>
<body>
<div id="content">
<svg width="500" height="500">
<g transform="translate(0, 0)"></g>
</svg>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
var width = 500, height = 500;
var colorScale = ['orange', 'lightblue', '#B19CD9',' white'];
var radius = width/2,
strokeWidth = 1,
hyp2 = Math.pow(radius, 2),
nodeBaseRad = 4;
var numNodes = 1000;
var nodes = d3.range(numNodes).map(function(d, i) {
return {
radius: nodeBaseRad,
category: i % 4
}
});
var xCenter = [0, radius*2, 0, radius*2]
var yCenter = [0, 0, radius*2, radius*2]
var simulation = d3.forceSimulation(nodes)
.force('charge', d3.forceManyBody().strength(5))
.force('x', d3.forceX().x(function(d) {
return xCenter[d.category];
}))
.force('y', d3.forceY().y(function(d) {
return yCenter[d.category];
}))
.force('collision', d3.forceCollide().radius(function(d) {
return d.radius + 0.5;
}).iterations(2))
.on('tick', ticked);
d3.select('svg g').append('circle').attr('r', radius)
.attr('cx', width/2)
.attr('cy', height/2)
function ticked() {
var u = d3.select('svg g')
.selectAll('circle.node')
.data(nodes);
u.enter()
.append('circle')
.attr('class', 'node')
.attr('r', function(d) {
return d.radius;
})
.style('fill', function(d) {
return colorScale[d.category];
})
.style('stroke', 'red')
.style('stroke-width', '1px')
.merge(u)
.attr('cx', function(d) {
return d.x = pythag(d.radius, d.y, d.x);
})
.attr('cy', function(d) {
return d.y = pythag(d.radius, d.x, d.y);
})
u.exit().remove();
}
function pythag(r, b, coord) {
r += nodeBaseRad;
// force use of b coord that exists in circle to avoid sqrt(x<0)
b = Math.min(width - r - strokeWidth, Math.max(r + strokeWidth, b));
var b2 = Math.pow((b - radius), 2),
a = Math.sqrt(hyp2 - b2);
// radius - sqrt(hyp^2 - b^2) < coord < sqrt(hyp^2 - b^2) + radius
coord = Math.max(radius - a + r + strokeWidth,
Math.min(a + radius - r - strokeWidth, coord));
return coord;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment