如何在html div标签中使用三个JS

时间:2019-01-21 11:18:13

标签: three.js

我使用domElement将数据附加到窗口中。但是如何使用html div标签将其附加到窗口?

我得到了错误

  

无法读取null的属性'appendChild'

我无法在div元素中附加我的三个js代码。

 <html>
<head>
    <title>
        Ajay's Beginners guide
    </title>
</head>

<body>
    <script src="../build/three.js"></script>
    <script>
        var scene, camera, renderer;
        function init() {
            var scene = new THREE.Scene();
            var WIDTH = window.innerWidth,
                HEIGHT = window.innerHeight;
        }
        renderer = new THREE.WebGLRenderer();
        // renderer.setSize(WIDTH, HEIGHT);
        console.log(document.body);
        canvas = document.getElementById('mycanvas');
        canvas.appendChild(renderer.domElement);
        renderer.setClearColorHex(0x333F47, 1);
        //color and opacity

        var light = new THREE.PointLight(0xffffff);
        light.position.set(-100, 200, 100);
        scene.add(light);

        camera = new THREE.PerspectiveCamera(45, WIDTH / HEIGHT, 0.1, 2000);
        camera.set.position(0, 6, 0);
        scene.add(camera);

        var loader = new THREE.JSONLoader();
        loader.load("models/treehouse_logo.js", function (geometry) {
            var material = new THREE.MeshLambertMaterial({ color: ox55B663 });
            mesh = new THREE.Mesh(geometry, material);
            scene.add(mesh);
        });

        controls = new THREE.OrbitControls(camera, render.domElement);

        window.addEventListener('resize', function () {
            var WIDTH = window.innerWidth;
            var HEIGHT = window.innerHeight;
            renderer.setSize(WIDTH, HEIGHT);
            camera.aspect = WIDTH / HEIGHT;
            camera.updateProjectionMatrix();
        });

        // init();
        function animate() {
            requestAnimationFrame();
            renderer.render(scene, camera);
            controls.update();
        }
    </script>
    <div id="mycanvas">
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

从评论移至答案,感谢@Marquizzo的建议。

您的脚本存在于body“画布”元素之前的div中。浏览器按顺序(大部分)解析页面。因此,您可以将脚本移动到div下方,以便在执行代码时可以将其附加到当前为 null 的位置。

这里是指向相关堆栈问题的链接,该链接关于在将页面内容钩入代码之前等待页面内容:Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it