A simple guide to getting started with Matter.js

Install

Download the edge build (master) or get a stable release and include the script in your web page:

  1. <script src="matter.js"></script>

For the latest features try the edge version (master), but it may not be fully stable.

You can also install using the package managers Bower and NPM.

  1. bower install matter-js
  2. npm install matter-js

Usage example

The following is a minimal example using the built in renderer and runner to get you started:

  1. // module aliases
  2. var Engine = Matter.Engine,
  3. Render = Matter.Render,
  4. World = Matter.World,
  5. Bodies = Matter.Bodies;
  6.  
  7. // create an engine
  8. var engine = Engine.create();
  9.  
  10. // create a renderer
  11. var render = Render.create({
  12. element: document.body,
  13. engine: engine
  14. });
  15.  
  16. // create two boxes and a ground
  17. var boxA = Bodies.rectangle(400, 200, 80, 80);
  18. var boxB = Bodies.rectangle(450, 50, 80, 80);
  19. var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });
  20.  
  21. // add all of the bodies to the world
  22. World.add(engine.world, [boxA, boxB, ground]);
  23.  
  24. // run the engine
  25. Engine.run(engine);
  26.  
  27. // run the renderer
  28. Render.run(render);

Include the above script into a page that has Matter.js installed and then open the page in your browser. Make sure the script is at the bottom of the page (or called on the window load event, or after DOM is ready).

Hopefully you will see two rectangle bodies fall and then hit each other as they land on the ground.If you don't, check the browser console to see if there are any errors.

Check out the demo page for more examples and then refer to Demo.js to see how they work. Some of the demos are also available on codepen, where you can easily experiment with them (but they may not always be completely up to date).

Running and Rendering

The above example uses the built in renderer and runner, but these are both optional and it's easy to render in your own way and use your own game loop.See the Rendering and Running wiki pages for information.

Documentation

See the Matter.js Documentation for detailed information on the API.