Public
Edited
Mar 3, 2024
1 fork
1 star
Insert cell
Insert cell
// Set Up the Canvas: Create a canvas element where the animation will take place.
canvas = {
const context = DOM.context2d(500, 500);
context.fillStyle = "black";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
return context.canvas;
}

Insert cell
Insert cell
function createParticle(x, y, vx, vy) {
return { x, y, vx, vy };
}

Insert cell
Insert cell
particles = Array.from({ length: 1000 }, () => createParticle(
Math.random() * canvas.width,
Math.random() * canvas.height,
(Math.random() - 0.5) * 4,
(Math.random() - 0.5) * 4
));

Insert cell
Insert cell
function updateParticles(particles) {
particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
// Implement boundary conditions
if (p.x > canvas.width) p.x = 0;
if (p.y > canvas.height) p.y = 0;
if (p.x < 0) p.x = canvas.width;
if (p.y < 0) p.y = canvas.height;
});
}

Insert cell
Insert cell
function drawParticles(context, particles) {
context.fillStyle = "white";
particles.forEach(p => {
context.beginPath();
context.arc(p.x, p.y, 1, 0, Math.PI * 2);
context.fill();
});
}

Insert cell
Insert cell
{
// Use the canvas from the canvas cell
const context = canvas.getContext("2d");
// Define the update loop
function update() {
updateParticles(particles); // Update particle positions
context.fillStyle = "black";
context.fillRect(0, 0, context.canvas.width, context.canvas.height); // Clear the canvas
drawParticles(context, particles); // Draw particles
}

// Run the update loop at a set interval
const interval = setInterval(update, 1000 / 60);
// Cleanup on cell re-evaluation
return () => clearInterval(interval);
}

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