p5.js
Gravity Well
Two hundred stars, one well of gravity. Touch the canvas and the well jumps to your finger — the whole sky follows. Let go and it settles back into orbit.
Licence: CC BY-NC-SA 4.0: remix with credit, non-commercial, share alike
View the code
// Gravity Well — a p5.js piece you can touch
// Stars orbit a gravity well. The well follows your finger (or mouse);
// leave it alone and it drifts on its own. Palette: charcoal, bone, signal orange.
// Site sliders: Gravity · Stars · Trails · Spin — read through params.*
const BONE = [233, 229, 218];
const ORANGE = [255, 180, 84];
const BG = [13, 13, 18];
let parts = [];
function setup() {
createCanvas(windowWidth, windowHeight);
background(...BG);
}
function accelAt(d) {
const G = (params.gravity ?? 1) * 1500;
return G / (d * d + 2600);
}
function wellPos() {
if (mouseX > 0 && mouseY > 0) return [mouseX, mouseY];
return [
width / 2 + cos(frameCount * 0.002) * width * 0.05,
height / 2 + sin(frameCount * 0.0026) * height * 0.05
];
}
function spawn(w) {
const a = random(TWO_PI);
const r = random(110, max(width, height) * 0.44);
const x = w[0] + cos(a) * r;
const y = w[1] + sin(a) * r;
const v = sqrt(accelAt(r) * r) * (params.spin ?? 0.7) * random(0.8, 1.12);
return {
x, y, px: x, py: y,
vx: -sin(a) * v, vy: cos(a) * v,
orange: random() < 0.8
};
}
function draw() {
noStroke();
fill(BG[0], BG[1], BG[2], params.trails ?? 9);
rect(0, 0, width, height);
const w = wellPos();
const want = round(params.stars ?? 220);
while (parts.length < want) parts.push(spawn(w));
if (parts.length > want) parts.splice(0, parts.length - want);
for (const p of parts) {
const dx = w[0] - p.x, dy = w[1] - p.y;
const d = max(20, Math.hypot(dx, dy));
const a = accelAt(d);
p.vx += (dx / d) * a;
p.vy += (dy / d) * a;
p.px = p.x; p.py = p.y;
p.x += p.vx; p.y += p.vy;
const sp = Math.hypot(p.vx, p.vy);
if (p.orange) stroke(ORANGE[0], ORANGE[1], ORANGE[2], 150);
else stroke(BONE[0], BONE[1], BONE[2], 115);
strokeWeight(sp > 3.2 ? 1.8 : 1.15);
line(p.x - p.vx * 2.0, p.y - p.vy * 2.0, p.x, p.y);
if (d < 24 || d > max(width, height) * 0.9) Object.assign(p, spawn(w));
}
noStroke();
fill(255, 216, 150, 235);
ellipse(w[0], w[1], 6);
}
function keyPressed() {
if (key === 's' || key === 'S') saveCanvas('gravity-well', 'png');
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
background(...BG);
}