Angular | Getting Started with matter.js

Matter.js is a 2D rigid body physics engine for the web written in JavaScript.

Creating an angular app with pages using matter.js is easy. Complete code is here.

For a more details post, please take a look at here: Angular | Working with matter.js


Create starter app

First, create a default angular app with ng new.

❯ ng new app-starter
? Do you want to enforce stricter type checking and stricter bundle budgets in the workspace?
  This setting helps improve maintainability and catch bugs ahead of time.
  For more information, see Yes
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS
cd app-starter

Add matter.js

Matter.js is a javascript library, so we have to add the corresponding files to our angular app. We will use the npm module matter-js.

npm install matter-js

We also add the type definitions, so that Visual Studio code knows how to check our code.

npm install @types/matter-js --save-dev 

Clear content of app.component.html

To keep out demopage clean, we will remove unnecessary code from app.component.html.

Remove all of the content and just keep the last line


Create pager for MatterJS democode

We will use a seperate Angular component/page for our matter.js demo

 ng generate component pages/Demo


Next, we add a routing for our demopage.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DemoComponent } from './pages/demo/demo.component';

const routes: Routes = [
  { path: 'demo', component: DemoComponent },
  { path: '',   redirectTo: '/demo', pathMatch: 'full' },
  { path: '**', redirectTo: '/demo', pathMatch: 'full' },

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
export class AppRoutingModule {}

Start App

Ready to take a first look at our app.

yarn start


Now, we do a little styling

.demo {
    background-color: lightgray;
    border: 4 dotted black;


And finally the matter.js code. Starting with the default imports for a angular app

import { Component, OnInit } from '@angular/core'

Next, we import the required matter.js parts

import { Engine, Runner, Render, World, Constraint, MouseConstraint, Bodies} from 'matter-js'

Following the definition for our DemoComponent

	selector: 'app-minimal',
	templateUrl: './demo.component.html',
	styleUrls: ['./demo.component.scss'],
export class DemoComponent implements OnInit {
	constructor() {}

	ngOnInit() {

	demo() {

The main code of out demo will be in the function demo()

	demo() {
		var engine = Engine.create()
		var render = Render.create({
			element: document.body,
			engine: engine,
			options: {
				width: 800,
				height: 400,
				wireframes: false,

		var boxA = Bodies.rectangle(400, 200, 80, 80)
		var ballA =, 100, 40, {})
		var ballB =, 10, 40, {})
		var ground = Bodies.rectangle(400, 380, 810, 60, {
			isStatic: true,

		World.add(, [boxA, ballA, ballB, ground])