Search code examples
javascripthtmlcanvasphysics-enginematter.js

How to make minimal example of matter.js work?


I'm trying to use the matter.js physics library. I'm using their "getting started" tutorial, but it can't find the canvas.

Here is my html:

<html>
<head>
<meta charset="UTF-8">
<title>Physics test</title>
</head>
<script type="text/javascript" src="./lib/matter-0.8.0.js"></script>
<script type="text/javascript">
// Matter.js module aliases
var Engine = Matter.Engine,
    World = Matter.World,
    Bodies = Matter.Bodies;

// create a Matter.js engine
var engine = Engine.create(document.body);

// create two boxes and a ground
var boxA = Bodies.rectangle(400, 200, 80, 80);
var boxB = Bodies.rectangle(450, 50, 80, 80);
var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });

// add all of the bodies to the world
World.add(engine.world, [boxA, boxB, ground]);

// run the engine
Engine.run(engine);
</script>
<body>
</body>
</html>

The console shows the following error:

" [Matter] warn: No "render.element" passed, "render.canvas" was not inserted into document."

I tried to create the render.element and render.canvas, but I'm acting blindly. A "minimal example to get you started" should be already working. What am I doing wrong?


Solution

  • Taking off part by part of the demo, I found out that most of the code should be in a function, called in the page load, like:

    <body onload='Start()'>
    

    and

    function Start() {
        // create a Matter.js engine
        var engine = Engine.create(document.getElementById('canvas-container'));
    
        // create two boxes and a ground
        var boxA = Bodies.rectangle(400, 200, 80, 80);
        var boxB = Bodies.rectangle(450, 50, 80, 80);
        var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });
    
        // add all of the bodies to the world
        World.add(engine.world, [boxA, boxB, ground]);
    
        // run the engine
        Engine.run(engine);
    }