Skip to content

Instantly share code, notes, and snippets.

@paulgb
Last active December 31, 2016 18:59
Show Gist options
  • Save paulgb/2076816d87243c189f885afe215e950b to your computer and use it in GitHub Desktop.
Save paulgb/2076816d87243c189f885afe215e950b to your computer and use it in GitHub Desktop.
Hot Air Rises
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
maxSize = 5
coreSize = 10
points = 600
data = new Array(points).fill().map((_, i) =>
{return {
radius: i % 50 == 0 ? maxSize : maxSize / 2,
x: 200 * Math.cos(2 * Math.PI * i / points),
y: 200 * Math.sin(2 * Math.PI * i / points)
}})
data.unshift({radius: coreSize, fx: 0, fy: 0})
colors = d3.scaleLinear().domain([0,maxSize,coreSize])
.range(['#00f', '#f00', '#CCC'])
function jitter(amount) {
nodes = []
force = function (alpha) {
for (node of nodes) {
node.vx += (Math.random() -0.5) * alpha * amount;
node.vy += (Math.random() - 0.5) * alpha * amount;
}
}
force.initialize = function(_nodes) {
nodes = _nodes;
}
return force;
}
height = 505
width = 960
circles = d3.select('body').append('svg')
.attr('height', height)
.attr('width', width)
.style('background-color', '#eee')
.append('g')
.attr('transform',
`translate(${width/2} ${height/2})`)
.selectAll('*')
.data(data)
.enter()
.append('circle')
.attr('fill', (d) => colors(d.radius))
.attr('r', 3)
d3.forceSimulation(data)
.force('gravity', d3.forceY(0).strength(0.08))
.force('gravity2', d3.forceX(0).strength(0.08))
.force('jitter', jitter(0.1))
.force('collision', d3.forceCollide((d) => Math.pow(d.radius, 1.3) / 1))
.alpha(0.125)
.alphaDecay(0)
.on('tick', () => {
circles
.attr('cx', (d) => d.x * 1.5)
.attr('cy', (d) => d.y * 1.5)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment