A two-dimensional port into JavaScript of the popular Traer Physics Library from Processing.


Development Version
Uncompressed with comments about 25kb

Production Version
Minified using Closure Compiler about 12kb

Or check out the source code on github.


There are many great physics engines out there for JavaScript, so why go and make this one? And, more importantly why would I use this?

Basic Usage

When using Physics there are a few core concepts that make developing much easier:

  1. When you make a new Physics, this represents the world in which all simulated interactions take place.
  2. There are three main inhabitants of this world: Physics.Particle, Physics.Attraction, and Physics.Spring.
  3. Physics is Physics.ParticleSystem with a few helper methods added. See documentation for specifics.

Now knowing this, let's move forward and create some simulations. N.B: All simulations for this section require canvas2d to draw objects.

Particle in situ

First, we're going to make a new space for physics to take place. This physics will have gravity and we will add a particle to it — when the particle falls out of viewer's sight we'll place it back where it started:

Physics.Particle Usage


The previous example showed physics with gravity, a constant force applied to all particles in the simulation. However, this isn't necessary. Now we'll create a physics without gravity and two particles. Instead of gravitational force we'll define a different type of behavior for the particles to exhibit, attraction:

Physics.Attraction Usage

Notice the particles continue to be attracted to each other.


Another more tactile behavior is known as a spring. Particles connected via a spring aim to always be at a specified rest distance from each other. In this example we'll create a spring with a rest distance smaller than the distance between the two particles. When the particles arrive at a state of rest, we'll reset the simulation by setting the positions of the particles to their original values:

Physics.Spring Usage


We just saw some basic canvas2d use cases, but Physics is renderer agnostic. This means that it only stores positions, how you draw those positions and relationships are up to you! In addition there are many other nuances and techniques that Physics can simulate. Below are just a few examples in different HTML rendering contexts and more advanced simulations to give you an idea:



Physics is not possible without these great contributions to JavaScript: