Aller au contenu principal

Rendering

Once your simulation is running, you need to draw it on the screen. Both verlet-engine and verlet-react use the HTML5 Canvas API for rendering, but they approach it differently.

Default Rendering

For many cases, the default, built-in rendering is all you need.

The <VerletCanvas> component handles rendering automatically. It finds all particles and constraints in your simulation and draws them with a default style. This is the easiest way to get started.

// The points and constraints are drawn automatically.
<VerletCanvas width={600} height={400}>
<Point id="p1" pos={new Vec2(200, 100)} pinned />
<Point id="p2" pos={new Vec2(300, 100)} />
<DistanceConstraint from="p1" to="p2" />
</VerletCanvas>

You can customize the appearance by passing a style prop to <Point> and constraint components.

Custom Rendering

If you need more control over the appearance of your simulation, you can provide a custom rendering function.

The <VerletCanvas> component accepts a customRenderer prop. This function gives you direct access to the canvas ctx and the array of composites on every frame. When you provide this prop, the default renderer is disabled.

import React from 'react';
import { VerletCanvas, Point } from 'verlet-react';
import { Vec2 } from 'verlet-engine';

const myCustomRenderer = (ctx, composites) => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

ctx.fillStyle = 'red';
for (const c of composites) {
for (const p of c.particles) {
// Draw all particles as red squares
ctx.fillRect(p.pos.x - 5, p.pos.y - 5, 10, 10);
}
}
};

const App = () => {
return (
<VerletCanvas width={600} height={400} customRenderer={myCustomRenderer}>
<Point id="p1" pos={new Vec2(300, 200)} />
</VerletCanvas>
);
};