Below is an example of an HTML Canvas particle “magnetism” simulation that uses the
[p5.js] or JavaScript + canvas approach with [dat.GUI] for live‐tuning. In this example the
particle “types” are defined as in your snippet. Each type “knows” how many connections it can
form with particles of each other type, and when two particles are close enough the code first
counts “connections” per type. Then, during the physics step the force between two particles is
made attractive if the current number of connections for that type is below the allowed number,
and repulsive (“anti‐magnet”) once the number of nearby connections equals or exceeds the allowed
capacity. (You can tweak the rules and distance criteria as needed.)
Below is a complete working example. (Open it in your browser to see it run.) Note that this is a
simplified simulation; feel free to adjust the physics details, the connection radius, and how the
“allowed connections” come into play in the force‐calculation logic.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Particle Magnetic Simulation</title>
<style>
/* Make canvas full screen */
body {
margin: 0;
overflow: hidden;
background: #111;
}
canvas {
display: block;
}
</style>
</head>
<body>
<!-- Canvas element -->
<canvas id="canvas"></canvas>
<!-- Include dat.GUI from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.min.js"></script>
<script>
/******************
* Global Settings
******************/
const settings = {
spawnRate: 1, // particles per second
globalAttraction: 1000, // global magnetic force multiplier
initialVelocity: 2, // speed of newly spawned particles (px/frame)
mass: 1, // mass multiplier for new particles
size: 1, // size multiplier for new particles
connectionDistance: 100, // distance below which particles count as connected
damping: 0.99, // velocity damping per frame
};
// Particle type definitions (each type also encodes allowed connections)
// Format: {type, forceMul, m, s, colorHSL: [h, s, l], connections: [...] }
const particleTypes = [
{ type: 0, forceMul: 3, m: 1, s: 10, colorHSL: [0, 50, 50], connections: [2, 1] },
{ type: 1, forceMul: 0.5, m: 1, s: 10, colorHSL: [72, 80, 70], connections: [0, 6, 2] },
{ type: 2, forceMul: 1, m: 1, s: 10, colorHSL: [180, 40, 80], connections: [1, 2, 3] },
{ type: 3, forceMul: 1, m: 1, s: 20, colorHSL: [252, 50, 90], connections: [2, 4] },
{ type: 4, forceMul: 1, m: 1, s: 10, colorHSL: [72, 0, 90], connections: [1, 1, 1, 1, 1] },
];
/**************************************
* Particle Class Definition
**************************************/
class Particle {
constructor(type, x, y, vx, vy) {
this.type = type;
// Use the type-defined attributes modified by settings
this.mass = particleTypes[type].m * settings.mass;
this.size = particleTypes[type].s * settings.size;
this.colorHSL = particleTypes[type].colorHSL;
this.forceMul = particleTypes[type].forceMul;
// Store allowed connections array.
// The index in the array corresponds to the neighbor’s type.
this.allowedConnections = particleTypes[type].connections;
// Position and velocity:
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
}
draw(ctx) {
// convert HSL values to an HSL color string
let [h, s, l] = this.colorHSL;
ctx.fillStyle = `hsl(${h}, ${s}%, ${l}%)`;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
/**************************************
* Simulation Setup and Variables
**************************************/
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = (canvas.width = window.innerWidth);
let ch = (canvas.height = window.innerHeight);
// Array to hold particles
const particles = [];
let lastSpawnTime = performance.now();
// For responsiveness:
window.addEventListener("resize", () => {
cw = canvas.width = window.innerWidth;
ch = canvas.height = window.innerHeight;
});
/**************************************
* dat.GUI Setup
**************************************/
const gui = new dat.GUI();
gui.add(settings, "spawnRate", 0.1, 10).name("Spawn Rate");
gui.add(settings, "globalAttraction", 0, 5000).name("Attraction");
gui.add(settings, "initialVelocity", 0, 10).name("Initial Velocity");
gui.add(settings, "mass", 0.1, 5).name("Particle Mass");
gui.add(settings, "size", 0.5, 3).name("Particle Size");
gui.add(settings, "connectionDistance", 10, 300).name("Connection Dist");
gui.add(settings, "damping", 0.90, 1).name("Velocity Damping");
/**************************************
* Utility Functions
**************************************/
// Returns a random number between min and max.
function rand(min, max) {
return Math.random() * (max - min) + min;
}
// Spawns a new particle at a random position along the canvas border.
function spawnParticle() {
// Randomly choose a type between 0 and particleTypes.length - 1:
const type = Math.floor(rand(0, particleTypes.length));
// Spawn along a random edge
let x, y;
const edge = Math.floor(rand(0, 4));
if (edge === 0) {
// Top edge
x = rand(0, cw);
y = 0;
} else if (edge === 1) {
// Right edge
x = cw;
y = rand(0, ch);
} else if (edge === 2) {
// Bottom edge
x = rand(0, cw);
y = ch;
} else {
// Left edge
x = 0;
y = rand(0, ch);
}
// Give it an initial velocity at a random angle:
const angle = rand(0, Math.PI * 2);
const speed = settings.initialVelocity;
const vx = Math.cos(angle) * speed;
const vy = Math.sin(angle) * speed;
particles.push(new Particle(type, x, y, vx, vy));
}
/**************************************
* Simulation: Force Calculation
**************************************/
// For each frame we do two passes:
// 1. Count the existing connections for each particle.
// 2. For each pair calculate force based on whether they are below or above
// the allowed connection count.
function simulate() {
// First, clear a connection count dictionary for every particle.
// We maintain an array "connectionsCount" parallel to the particles array.
// Each entry is an object mapping neighbor type => count of connected particles.
const connectionsCount = particles.map(() => ({}));
// Count connections based solely on distance threshold.
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const pa = particles[i];
const pb = particles[j];
const dx = pb.x - pa.x;
const dy = pb.y - pa.y;
const dist = Math.hypot(dx, dy);
if (dist < settings.connectionDistance) {
// Count for particle a with respect to pb type:
connectionsCount[i][pb.type] = (connectionsCount[i][pb.type] || 0) + 1;
// And for particle b with respect to pa type:
connectionsCount[j][pa.type] = (connectionsCount[j][pa.type] || 0) + 1;
}
}
}
// Now, for every pair, apply force based on connection counts and allowed capacity.
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const pa = particles[i];
const pb = particles[j];
const dx = pb.x - pa.x;
const dy = pb.y - pa.y;
const dist = Math.hypot(dx, dy);
if (dist < 0.1) continue; // avoid division by zero
// Unit vector from a to b:
const ux = dx / dist;
const uy = dy / dist;
// Determine allowed connections from particle a for pb's type.
let allowedA = pa.allowedConnections[pb.type] || 0;
let currentA = connectionsCount[i][pb.type] || 0;
// From particle b for pa's type:
let allowedB = pb.allowedConnections[pa.type] || 0;
let currentB = connectionsCount[j][pa.type] || 0;
// Decide force polarity:
// If connections are lower than allowed, we attract; if equal or above, repel.
const polarityA = currentA < allowedA ? 1 : -1;
const polarityB = currentB < allowedB ? 1 : -1;
// Average the polarity or you could combine them differently:
const polarity = (polarityA + polarityB) / 2;
// Calculate force magnitude. We use an inverse–square law.
// The particle’s force multiplier and a global multiplier are used.
// (The constant (settings.globalAttraction) can be tuned via dat.GUI.)
const forceMagnitude =
(settings.globalAttraction *
pa.forceMul *
pb.forceMul *
polarity) /
(dist * dist);
// Because the force acts on both particles in opposite directions,
// update velocities (acceleration = force/mass).
const ax = (forceMagnitude * ux) / pa.mass;
const ay = (forceMagnitude * uy) / pa.mass;
const bx = -(forceMagnitude * ux) / pb.mass;
const by = -(forceMagnitude * uy) / pb.mass;
pa.vx += ax;
pa.vy += ay;
pb.vx += bx;
pb.vy += by;
}
}
}
/**************************************
* Update & Draw Loop
**************************************/
function update() {
// Spawn particles according to spawnRate
const now = performance.now();
const elapsed = (now - lastSpawnTime) / 1000; // in seconds
if (elapsed >= 1 / settings.spawnRate) {
spawnParticle();
lastSpawnTime = now;
}
// Update positions based on velocity
for (let p of particles) {
p.x += p.vx;
p.y += p.vy;
// Simple damping for stability:
p.vx *= settings.damping;
p.vy *= settings.damping;
// Wrap-around the borders:
if (p.x < 0) p.x += cw;
if (p.x > cw) p.x -= cw;
if (p.y < 0) p.y += ch;
if (p.y > ch) p.y -= ch;
}
}
function draw() {
// Clear canvas (semi-transparent black for trails effect)
ctx.fillStyle = "rgba(17,17,17,0.3)";
ctx.fillRect(0, 0, cw, ch);
// Draw all particles
for (let p of particles) {
p.draw(ctx);
}
}
function loop() {
simulate();
update();
draw();
requestAnimationFrame(loop);
}
// Kick off the simulation loop.
loop();
</script>
</body>
</html>
Explanation
-
Particle Types and Connections:
The particleTypes array holds each type’s properties. The connections array for a type (for example, type 0 has [2,1]) means that a particle of type 0 “wants” to form up to 2 connections with type 0s and 1 connection with type 1 particles. In our simulation the code first checks for nearby particles (within the connectionDistance) and counts how many of each connection type already exist. Then in the force loop we decide that if the number of connections so far is less than allowed, the interaction is attractive; otherwise the force reverses to repulsion.
-
Global Settings and dat.GUI Controls:
The settings object contains simulation parameters such as the spawn rate, global attraction strength, initial velocity, mass and size multipliers, connection distance and damping. The dat.GUI controls allow you to tweak these live.
-
Spawning and Particle Movement:
New particles are spawned along the canvas border at a rate controlled by settings.spawnRate. They are given a random direction with the magnitude defined by settings.initialVelocity. Each particle’s physical properties (mass, size, and color) are derived from its type and the corresponding multipliers from settings.
-
Force Calculation:
In each simulation step, the code:
- First counts “connections” (particles that are close enough) for every particle.
- Then for every pair of particles, it computes a force based on whether their current number of “connections” is below (yielding attraction) or at/above (yielding repulsion) the allowed number.
The global attraction strength (settings.globalAttraction) and the type-specific forceMul values modulate the force’s strength.
-
Animation Loop and Drawing:
The simulation loop uses requestAnimationFrame to:
- Compute forces,
- Update particle positions,
- And redraw everything on the canvas.
A slight “trail” effect is produced by drawing a semi-transparent rectangle over the canvas each frame.
Feel free to modify the physics rules and relationship between connection counts and force polarity as needed; this sample is a starting point matching the ideas you described.