Published
Edited
Nov 13, 2018
1 star
Insert cell
Insert cell
{
const w = width;
const h = 240;
const ctx = DOM.context2d(w, h);
const state = {
minGravR: 20,
a: { x: w * 0.5, vx: 0, m: 100, r: 30, color: "yellow" },
b: { x: w * 0.75, vx: 0, m: 1, r: 10, color: "cornflowerblue" }
};
function draw() {
const y = h / 2;
const { a, b } = state;
const r = 10;
ctx.save();
ctx.fillStyle = "#333";
ctx.fillRect(0, 0, w, h);
ctx.beginPath();
ctx.arc(a.x, y, a.r, 0, 2 * Math.PI);
ctx.fillStyle = a.color;
ctx.fill();
ctx.beginPath();
ctx.arc(b.x, y, b.r, 0, 2 * Math.PI);
ctx.fillStyle = b.color;
ctx.fill();
ctx.restore();
}
function getGravityAcc(me, other) {
// F = GMm/r^2
// => Ma = GMm/r^2
// => a = Gm/r^2
const G = 0.01;
const r = other.x - me.x;
if (Math.abs(r) < state.minGravR) return 0;
const a = (G * other.m) / r ** 2;
return a * Math.sign(r);
}
const dt = 1000 / 60;
function update() {
// Performing many steps per frame helps us increase accuracy
// without making us use Runge Kutta or Verlet integration.
const steps = 40;
const _dt = dt / steps;
for (let i = 0; i < steps; i++) {
state.a.vx += getGravityAcc(state.a, state.b) * _dt;
state.b.vx += getGravityAcc(state.b, state.a) * _dt;
state.a.x += state.a.vx * _dt;
state.b.x += state.b.vx * _dt;
}
draw();
}
const interval = setInterval(update, dt);
invalidation.then(() => clearInterval(interval));
return ctx.canvas;
}
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more