Public
Edited
Jun 6, 2024
1 star
Also listed in…
regl
Insert cell
Insert cell
canvas = DOM.canvas(width, 420)
Insert cell
regl.frame(() => {
// Clear the canvas
regl.clear({
color: [0, 0, 0, 1],
depth: 1
});

// Update particle positions
for (let i = 0; i < numberOfParticles; i++) {
particleData[i * 4 + 0] += particleData[i * 4 + 2]; // Update x position
particleData[i * 4 + 1] += particleData[i * 4 + 3]; // Update y position

// Bounce off walls
if (particleData[i * 4 + 0] > 1 || particleData[i * 4 + 0] < -1)
particleData[i * 4 + 2] *= -1;
if (particleData[i * 4 + 1] > 1 || particleData[i * 4 + 1] < -1)
particleData[i * 4 + 3] *= -1;
}

// Update the particle buffer with the new positions
particleBuffer.subdata(particleData);

// Draw the particles
drawParticles();
})
Insert cell
drawParticles = regl({
frag: `
precision mediump float;
void main() {
gl_FragColor = vec4(1, 1, 1, 1);
}`,

vert: `
precision mediump float;
attribute vec4 particle;
uniform float pointSize;
void main() {
gl_Position = vec4(particle.xy, 0, 1);
gl_PointSize = pointSize;
}`,

attributes: {
particle: particleBuffer
},

uniforms: {
pointSize: 2
},

count: numberOfParticles,
primitive: "points"
})
Insert cell
Insert cell
particleBuffer = regl.buffer(particleData)
Insert cell
particleData = {
const particles = new Float32Array(numberOfParticles * 4);

for (let i = 0; i < numberOfParticles; i++) {
particles[i * 4 + 0] = Math.random() * 2 - 1; // x position
particles[i * 4 + 1] = Math.random() * 2 - 1; // y position
particles[i * 4 + 2] = Math.random() * 0.005 - 0.005; // x velocity
particles[i * 4 + 3] = Math.random() * 0.005 - 0.005; // y velocity
}

return particles;
}
Insert cell
numberOfParticles = 10000
Insert cell
Insert cell
regl = (await import("https://cdn.skypack.dev/regl@2")).default({ canvas })
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