Skip to content

Instantly share code, notes, and snippets.

@vasturiano
Last active May 10, 2017 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasturiano/29550a65f206d513264e95c8ce2884ab to your computer and use it in GitHub Desktop.
Save vasturiano/29550a65f206d513264e95c8ce2884ab to your computer and use it in GitHub Desktop.
Particle Orbit
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.7.0/d3.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<svg id="canvas">
<g id="trail"></g>
<circle id="center" r="20" cx="0" cy="0"></circle>
<circle id="particle" r="8"></circle>
</svg>
<script>
const attractionForce = 0.001; // Regulates orbitting velocity
const width = window.innerWidth, height = window.innerHeight;
d3.select('#canvas')
.attr('width', width)
.attr('height', height)
.attr('viewBox', `${-width/2} ${-height/2} ${width} ${height}`);
var particle = { domCtx: d3.select('#particle') };
d3.forceSimulation()
.alphaDecay(0)
.velocityDecay(0)
.nodes([particle])
// Pull towards center with weak force
.force("centerX", d3.forceX().strength(attractionForce))
.force("centerY", d3.forceY().strength(attractionForce))
.on("tick", () => {
particle.domCtx
.datum(particle)
.attr('cx', d => d.x)
.attr('cy', d => d.y)
});
// Add orbit trail
d3.timer(() => {
d3.select('#trail').append('circle')
.attr('r', 1.5)
.attr('cx', particle.x)
.attr('cy', particle.y)
.transition().duration(3500)
.style('opacity', 0)
.remove();
});
// Spin it
particle.y = -height / 3;
particle.vx = 0.55 * height * Math.sqrt(attractionForce);
</script>
</body>
body {
text-align: center;
font-family: Sans-serif;
margin: 0;
}
#particle {
fill: #203390;
}
#center {
fill: #ff4e2d;
}
#trail circle {
fill: darkgrey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment