Search code examples
javascripthtmlbabylonjs

Cannot set a texture to box (html5 / js / babylon.js)


I'm trying out Babylon.js. I want to set my floor texture but it doesn't work. I get the following error:

enter image description here

"Uncaught TypeError: _this.getScene is not a function" (for google search)

I really don't get this, the youtube tutorial made it seem so easy.

Source code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        #canvas {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script src="https://cdn.babylonjs.com/babylon.max.js"></script>
    <script>
        window.addEventListener('DOMContentLoaded', function () {
            var canvas = document.getElementById('canvas');
            var engine = new BABYLON.Engine(canvas, true);
            var createScene = function () {
                var scene = new BABYLON.Scene(engine);
                scene.clearColor = new BABYLON.Color3.White();

                var floor = BABYLON.MeshBuilder.CreateBox("floor", { height: 25, width: 800, depth: 900 }, scene);
                floor.position.y = -162.5;
                floor.position.x = 100;
                floor.position.z = 400;

                var camera = new BABYLON.ArcRotateCamera(
                    'camera1',
                    BABYLON.Tools.ToRadians(45),
                    BABYLON.Tools.ToRadians(45),
                    1000.0,
                    new BABYLON.Vector3(0, 50, 400),
                    scene);
                camera.attachControl(canvas, true);

                var light = new BABYLON.PointLight("pointlight", new BABYLON.Vector3(800, 700, 1000), scene);
                light.diffuse = new BABYLON.Color3(1, 1, 1);


                var floormaterial = new BABYLON.StandardMaterial("floormaterial", scene);
                floormaterial.diffuseTexture = BABYLON.Texture("floor.png", scene);
                floor.material = floormaterial;

                return scene;
            };

            var scene = createScene();
            engine.runRenderLoop(function () {
                scene.render();
            });

        });
    </script>
</body>
</html>

If I remove the "floormaterial.diffuseTexture = BABYLON.Texture("floor.png", scene);" line everything works perfectly.


Solution

  • you are missing the new before the texture. the line should be:

    floormaterial.diffuseTexture = new BABYLON.Texture("floor.png", scene);