Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

THREE.js does not render in the browser

I was watching the tutorial of creating a solar system using the THREE.js library. However I could not see the result in the browser's window. Could you, please, help me finding an error in the code?

Here is the code:

<!doctype html>
   <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Solar System - Intro (1)</title>
        <script src="three.min.js"></script>
    </head>

<body>

<script>
    var scene, camera, render, container, W, H;

    W = parseInt(document.body.clientWidth);
    H = parseInt(document.body.clientHeight);

    container = document.createElement('div');
    document.body.appendChild(container);

    camera = new THREE.PerspectiveCamera(45, W / H, 1, 10000);
    camera.position.z = 4300;
    scene = new THREE.Scene();

    // Sun
    var sun, sun_geom, sun_mat;
    sun_geom = new THREE.SphereGeometry(430, 30, 30);
    sun_mat = new THREE.MeshNormalMaterial();
    sun = new THREE.Mesh(sun_geom, sun_mat);
    scene.add(sun);

    render = new THREE.CanvasRenderer();
    render.setSize(W, H);
    container.appendChild(render.domElement);
    animate();

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

</body>

</html>

link to the video: https://www.youtube.com/watch?v=kzwEZjVMdkA&list=LLSn1erQiQ7lWhWY9IMOEGTw&index=5

like image 327
sheriff_paul Avatar asked Feb 11 '23 09:02

sheriff_paul


1 Answers

The issue with your code is that the document.body.clientHeight is 0. Use these lines instead:

W = parseInt(window.innerWidth);
H = parseInt(window.innerHeight);

In addition THREE.CanvasRenderer has been moved to examples/js/renderers/CanvasRenderer.js so you need to include that, if you want to use the CanvasRenderer()

But you can use the WebGLRenderer():

render = new THREE.WebGLRenderer();
like image 85
gaitat Avatar answered Feb 13 '23 00:02

gaitat