Getting Started
Let's get you up and running with your first Verlet.js simulation. Choose your preferred environment below.
- React
- JavaScript
1. Installation
npm install verlet-react verlet-engine
2. Create your Simulation
Use the <VerletCanvas> component to create a simulation world and add objects to it.
import React from 'react';
import { VerletCanvas, Point, DistanceConstraint } from 'verlet-react';
import { Vec2 } from 'verlet-engine';
const App = () => {
return (
<VerletCanvas width={500} height={500} gravity={{ x: 0, y: 0.5 }}>
<Point id="p1" pos={new Vec2(200, 50)} pinned />
<Point id="p2" pos={new Vec2(220, 50)} />
<Point id="p3" pos={new Vec2(240, 50)} />
<Point id="p4" pos={new Vec2(260, 50)} />
<DistanceConstraint from="p1" to="p2" />
<DistanceConstraint from="p2" to="p3" />
<DistanceConstraint from="p3" to="p4" />
</VerletCanvas>
);
};
export default App;
1. Installation
npm install verlet-engine
2. Create your Simulation
Create an HTML file with a <canvas> element, then use the VerletJS class to create a simulation.
<canvas id="verlet-canvas" width="500" height="500"></canvas>
import { VerletJS, Particle, Vec2, DistanceConstraint, PinConstraint } from 'verlet-engine';
const canvas = document.getElementById('verlet-canvas');
const ctx = canvas.getContext('2d');
const sim = new VerletJS(500, 500);
sim.gravity = new Vec2(0, 0.5);
// Create particles
const particles = [
new Particle(new Vec2(200, 50)),
new Particle(new Vec2(220, 50)),
new Particle(new Vec2(240, 50)),
new Particle(new Vec2(260, 50)),
];
// Create constraints
const constraints = [
new DistanceConstraint(particles[0], particles[1]),
new DistanceConstraint(particles[1], particles[2]),
new DistanceConstraint(particles[2], particles[3]),
new PinConstraint(particles[0], particles[0].pos), // Pin the first particle
];
sim.composites.push({ particles, constraints });
function animate() {
sim.frame();
ctx.clearRect(0, 0, 500, 500);
// Draw constraints
ctx.beginPath();
for (const c of constraints) {
if (c instanceof DistanceConstraint) {
ctx.moveTo(c.a.pos.x, c.a.pos.y);
ctx.lineTo(c.b.pos.x, c.b.pos.y);
}
}
ctx.stroke();
// Draw particles
ctx.beginPath();
for (const p of particles) {
ctx.moveTo(p.pos.x + 5, p.pos.y);
ctx.arc(p.pos.x, p.pos.y, 5, 0, 2 * Math.PI);
}
ctx.fill();
requestAnimationFrame(animate);
}
animate();