Public
Edited
Oct 6, 2024
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
canvas = {
const size = width / 1.5;
const context = DOM.context2d(size, size);

// R, Theta
const planet = [size / 4, 0];
const moon = [planet[0] * moonRadius, 0];
let counter = 0;
const speedFactor = 2e-3;

context.fillStyle = "#302010";
context.fillRect(0, 0, size, size);
context.lineWidth = 2;

// Our planets path is just an arc, but the moon is wobbly.
let pmx = undefined, pmy = undefined;
while (true) {
context.fillStyle = "#302010";
context.globalAlpha = 0.01;
context.save();

if (counter % 60 == 0) {
context.fillRect(0, 0, size, size);
}
context.globalAlpha = 1;
context.fillStyle = '#F5EBB0';
context.strokeStyle = '#7F4B61';
counter += 1;

// Set canvas origin
context.translate(size/2, size/2);

// Draw origin
context.beginPath();
context.arc(0, 0, 4, 0, 2 * Math.PI)
context.fill()
// Draw our planet path
context.beginPath();
context.arc(0, 0, planet[0], planet[1] - 0.8 + counter * speedFactor * speedPlanet, planet[1] + counter * speedFactor * speedPlanet);
context.stroke()
// Draw our moon path
context.strokeStyle = '#ACB852';
const [px, py] = toCartesian(planet[0], planet[1] + counter * speedFactor * speedPlanet);
const [_mx, _my] = toCartesian(moon[0], planet[1] + counter * speedFactor * speedMoon);
const mx = px + _mx;
const my= py + _my;
pmx = pmx === undefined ? mx : pmx;
pmy = pmy === undefined ? my : pmy;
console.log([pmx, pmy, mx, my])

context.beginPath();
context.moveTo(pmx, pmy);
context.lineTo(mx, my);
context.stroke();

context.restore()
pmx = mx;
pmy = my;
if (counter % 10 == 0) {
yield context.canvas;
}
}
}

Insert cell
height = 200
Insert cell
toCartesian(30, 3)
Insert cell
function toCartesian(r, theta) {
return [r * Math.cos(theta), r * Math.sin(theta)];
}

Insert cell

function toPolar(x, y) {
return [Math.atan2(y, x), Math.sqrt( x*x + y*y)];
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more