Search code examples
javascripthtmlgoogle-chromecanvasthree.js

Three.js example not displaying on canvas


i found an example of three.js and I am trying to implement it on a <canvas></canvas> element. I get a reference to the element but I dont get a visual. I have my canvas element with the Id of "mycanvas".

<canvas id="mycanvas" style="border: 5px solid white" width="600" height="500"></canvas>

an I use an onload function in the body called WebGLStart() which calls the script below.

   <script>
        function WebGLStart()
        {
            //Get the canvas and the context
            var canvas = document.getElementById('mycanvas');
            var canvas_context = canvas.getContext("webgl");
            console.log("Canvas: "+canvas.width);
            console.log("Canvas: "+canvas.height);

            var RENDER_DIST = 1000,
                FOV = 75;

            var WIDTH = canvas.width,
                HEIGHT= canvas.height;

            var scene = new THREE.Scene();


            var camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, 0.1, RENDER_DIST);

            camera.position.z = 100;

            scene.add(camera);

            renderer = new THREE.WebGLRenderer();
            renderer.setSize(WIDTH,HEIGHT); 
            console.log("R info: "+renderer.info);

            canvas.appendChild(renderer.domElement);

            init();
            loopRun();

            function init() 
            {
                var geometry = new THREE.SphereGeometry(50); 
                var material = new THREE.MeshBasicMaterial({color: 0xff0000}); 
                var sphere = new THREE.Mesh(geometry, material); 
                scene.add(sphere);
            }

            function loopRun() 
            {
                requestAnimationFrame(loopRun);
                renderer.render(scene, camera);
            }
        }
    </script>

Is there any reason why this would not display? I get outputs on chromes prompt(canvas width and height) but no display. any ideas would be appreciated


Solution

  • Child elements of the canvas element are not visible.

    To solve this attach the renderer DOM element to some other DOM element, e.g. document body.

    if you change this line:

    canvas.appendChild(renderer.domElement);
    

    to this:

    document.body.appendChild(renderer.domElement);
    

    You'll get the desired result.