As a web developer, you usually move in a rather static world. Elements are put in their place and then at most moved during a resize or a transition. That's okay most of the time, but sometimes it's just a bit too boring.
With matter.js the web world comes to life. Bodies with different properties can be placed in two-dimensional space. Matter.js simulates a physical environment so that these bodies interact with each other. The result of the simulations is then rendered into an HTML canvas.
This example is fairly simple in design: The square world contains two static rectangles. I have rotated these slightly and placed them in different places in the world so that they become obstacles.When the left button is clicked and initialized, the rain() function is executed.
It generates 40 circles via a for loop, which are then spawned above the visible area of the world and fall down. To make the whole thing a bit more interesting, I gave the circles two different sizes/masses and a slight push to the right.
Clicking the right button simply reverses the direction of gravity with one line of code, which also gives a very amusing effect.The story gets especially interesting when mouse interaction comes into play. This is simply added by an instance of MouseConstraint.
This example is only a small part of what you can do with matter.js. But here alone I've had a really good time playing around with physical parameters (mass, friction, gravity, force, etc.) and visual parameters (color, texture, etc.). Watching the realistic simulation is sometimes really satisfying.
- matter.js Website & Docs
- matter.js GitHub
- matter.js Demo Playground