Simulation of an orbitting body using the D3 force-directed physics engine.
Last active
May 10, 2017 18:31
-
-
Save vasturiano/29550a65f206d513264e95c8ce2884ab to your computer and use it in GitHub Desktop.
Particle Orbit
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
<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> |
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
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