0

I was practicing to make some animations with ThreeJS but it says "Uncaught TypeError: Cannot read properties of undefined (reading 'render')". I have no clue about this error. This is my first time using ThreeJS, so I don't know much about it.

<body>
<script src="main.js" type="module" defer></script>

<script type="module">
    import * as THREE from 'https://cdn.skypack.dev/three@0.124.0/build/three.module.js';
    let scene, camera, renderer, starGeo, stars;

    function init() {
      //create scene object
      const scene = new THREE.Scene();
      
      //setup camera with facing upward
      const camera = new THREE.PerspectiveCamera(60,window.innerWidth / window.innerHeight, 1, 1000);
      camera.position.z = 1;
      camera.rotation.x = Math.PI/2;
      
      //setup renderer
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

        starGeo = new THREE.Geometry();
            for(let i=0;i<6000;i++) {
                let star = new THREE.Vector3(
                Math.random() * 600 - 300,
                Math.random() * 600 - 300,
                Math.random() * 600 - 300
            );
            star.velocity = 0;
            star.acceleration = 0.02;
            starGeo.vertices.push(star);
            }
            let sprite = new THREE.TextureLoader().load( 'star.png' );
            let starMaterial = new THREE.PointsMaterial({
                color: 0xaaaaaa,
                size: 0.7,
                map: sprite
            });

            stars = new THREE.Points(starGeo,starMaterial);
            scene.add(stars);

      animate(); 
    }
    //rendering loop
    function animate() {
        starGeo.vertices.forEach(p => {
            p.velocity += p.acceleration
            p.y -= p.velocity;
            
            if (p.y < -200) {
            p.y = 200;
            p.velocity = 0;
            }
        });
    starGeo.verticesNeedUpdate = true;
    stars.rotation.y +=0.002;
    renderer.render(scene, camera);
    requestAnimationFrame(animate);
    }
    init();
 </script>

Thanks!

Reporter
  • 3,897
  • 5
  • 33
  • 47
  • 1
    You declare `let render;` and then never assign a value to it. Please see [What is the scope of variables in JavaScript?](/q/500431/4642212). – Sebastian Simon Oct 18 '22 at 10:27

1 Answers1

1

You need to change this line: const renderer = new THREE.WebGLRenderer(); To be: renderer = new THREE.WebGLRenderer();

The problem was that you never assigned a value to the let renderer at the higher scope and had another constant with the same name at the init() function scope which is not available in animate() function scope.

Ala Douagi
  • 1,035
  • 2
  • 10
  • 14