user14945188
user14945188

Reputation: 65

I cant use matter js on codepen

CodePen matter js error

Hello, I am trying to use Matter JS on codepen, I firstly received the error that the variable Matter was not defined, I already fixed this but another error came.

Code Preview:

import * as Matter from:
"https://cdn.skypack.dev/[email protected]";
let engine = Matter.engine.create();
let render = Matter.render.create({
  element: document.body,
  engine:engine
});
// and some more code...

Preview: https://codepen.io/Eslare/pen/NWRQXpx

The Error:
TypeError: undefined is not an object (evaluating 'Matter.engine.create')

Upvotes: 2

Views: 492

Answers (4)

8Observer8
8Observer8

Reputation: 1152

You can use importmap on another Sandboxes instead of CodePan:

index.html

<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Example</title>
</head>

<body style="caret-color: transparent;">
    <canvas id="renderCanvas" width="400" height="400"></canvas>

    <!-- Since import maps are not yet supported by all browsers, it is
        necessary to add the polyfill es-module-shims.js
        Source: https://threejs.org/docs/index.html#manual/en/introduction/Installation -->
    <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
    <script type="importmap">
        {
            "imports": {
                "gl-matrix": "https://cdn.jsdelivr.net/npm/[email protected]/+esm",
                "matter-js": "https://cdn.jsdelivr.net/npm/[email protected]/+esm"
            }
        }
    </script>

    <script type="module" src="js/main.js"></script>
</body>

</html>

js/main.js

import { mat4, vec3 } from "gl-matrix";
import { default as Matter } from "matter-js";

console.log(`Matter.js version: ${Matter.version}`);

Upvotes: 0

loop
loop

Reputation: 973

Here is how you import it properly from Skypack.dev

import { default as Matter } from 'https://cdn.skypack.dev/matter-js@^0.17.1';

https://codepen.io/codepen0980/pen/YzNoxvd?editors=0010

Upvotes: 1

Kidas
Kidas

Reputation: 329

here a modified version of your pen: https://codepen.io/sessaidi/pen/abmeEbV, you need to add an external resource: https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.14.2/matter.min.js

Upvotes: 0

Yalcin Kilic
Yalcin Kilic

Reputation: 800

Don't import it in your JS section, just go to the settings and add it as external script.

enter image description here

Upvotes: 1

Related Questions