Simulation of an orbitting body using the D3 force-directed physics engine.
forked from vasturiano's block: Particle Orbit
xxxxxxxxxx
<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>
https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.0/d3.min.js