最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Three.js, appendChild and returning - Stack Overflow

programmeradmin2浏览0评论

This is actually something I've solved, but for curiousity sake, I was wondering if someone could explain why this is the case?

Here's my html:

    <!DOCTYPE html>
    <html>

        <head>
            <script src="three.min.js"></script>
            <script src="OrbitControls.js"></script>
            <script type="text/javascript" src="webgl.js"></script>
        </head>

        <body style="margin: 0;">

        </body>

    </html>

and my JS:

    var scene, camera, renderer;

    init();

    animate();

    function init(){

        scene = new THREE.Scene();

        var width = window.innerWidth, height =  window.innerHeight;

        renderer = new THREE.WebGLRenderer({antialias:true});
        renderer.setSize(width, height);
        document.body.appendChild(renderer.domElement);

    }

This does not work, I get "Uncaught TypeError: Cannot read property 'appendChild' of null "

But when I move my webgl.js script to the body, it renders the canvas element properly.

Why does this happen? Why does my script need to be in the body to append the dom element? The renderer object returns an canvas in my console, so what's the issue?

This is actually something I've solved, but for curiousity sake, I was wondering if someone could explain why this is the case?

Here's my html:

    <!DOCTYPE html>
    <html>

        <head>
            <script src="three.min.js"></script>
            <script src="OrbitControls.js"></script>
            <script type="text/javascript" src="webgl.js"></script>
        </head>

        <body style="margin: 0;">

        </body>

    </html>

and my JS:

    var scene, camera, renderer;

    init();

    animate();

    function init(){

        scene = new THREE.Scene();

        var width = window.innerWidth, height =  window.innerHeight;

        renderer = new THREE.WebGLRenderer({antialias:true});
        renderer.setSize(width, height);
        document.body.appendChild(renderer.domElement);

    }

This does not work, I get "Uncaught TypeError: Cannot read property 'appendChild' of null "

But when I move my webgl.js script to the body, it renders the canvas element properly.

Why does this happen? Why does my script need to be in the body to append the dom element? The renderer object returns an canvas in my console, so what's the issue?

Share Improve this question asked Nov 7, 2014 at 19:47 jorblumejorblume 6077 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

When the script is called inside the head, the body does not exist yet. You can see this by calling console.log(document.body) in both the head and the body. You'll find that document.body is null because the body has yet to be created.

发布评论

评论列表(0)

  1. 暂无评论