Published
Edited
Mar 3, 2022
1 star
Insert cell
Insert cell
Insert cell
{
const canvasWidth = 720;
const canvasHeight = 540;

const canvas = DOM.canvas(canvasWidth, canvasHeight);

const p = new paper.PaperScope();
paper.setup(canvas);

const radius = 2;
let stars = [];
let circles = [];

for (let i = 0; i < 600; i++) {
const r = Math.random() * radius;
stars.push({
center: [Math.random() * canvasWidth, Math.random() * canvasHeight],
radius: r,
z: Math.random() * canvasWidth,
fillColor: "black"
});
circles.push(undefined);
}

// animation
paper.view.onFrame = () => {
for (let i = 0; i < stars.length; i++) {
let z = stars[i].z;

z = z - 1;

if (z <= 0) {
z = canvasWidth;
}

const center = stars[i].center;

let x = center[0],
y = center[1];

x = (x - canvasWidth / 2) * (canvasWidth / z);
x += canvasWidth / 2;

y = (y - canvasHeight / 2) * (canvasWidth / z);
y += canvasHeight / 2;

stars[i].center = [x, y];
stars[i].z = z;
stars[i].radius *= canvasWidth / z;

if (circles[i] !== undefined) {
circles[i].remove();
}

circles[i] = new p.Path.Circle({
center: stars[i].center,
radius: stars[i].radius,
fillColor: stars[i].fillColor
});

if (x < 0 || x > canvasWidth || y < 0 || y > canvasHeight) {
stars[i] = {
center: [Math.random() * canvasWidth, Math.random() * canvasHeight],
radius: Math.random() * radius,
z: Math.random() * canvasWidth,
fillColor: "black"
};
}
}
};

return canvas;
}
Insert cell
Insert cell
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