简体   繁体   中英

Three.js canvas not appearing to render, no errors

I've been wanting to use Three.js in a project but I can't get anything to render on my screen.

After a while of troubleshooting, I thought I would just ask and see if anyone can help me.

DETAILS: Hosting on XAMPP, here's a complete Three.js example that should work, to my knowledge, but evidently does not:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="c"></canvas>
    <script type="module">
    import {
        Camera,
        Material,
        Texture,
      } from "https://cdn.skypack.dev/three@0.132.2";
      
      import { OrbitControls } from "https://cdn.skypack.dev/three@0.132.2/examples/jsm/controls/OrbitControls.js";
      function main() {
          const canvas = document.getElementById('c');
          const renderer = new THREE.WebGLRenderer({canvas});
          const fov = 75;
          const aspect = 2;  // the canvas default
          const near = 0.1;
          const far = 5;
          const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
          camera.position.z = 2;
          const scene = new THREE.Scene();
          const boxWidth = 1;
          const boxHeight = 1;
          const boxDepth = 1;
          const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
          const material = new THREE.MeshBasicMaterial({color: 0x44aa88});
          const cube = new THREE.Mesh(geometry, material);
          scene.add(cube);
          renderer.setSize(window.innerWidth, window.innerHeight);
          renderer.render(scene, camera);
      }
    </script>
</body>
</html>

I've linked through a cdn here, but other methods such as installing with npm and linking that way have also had the same confounding results. In any case it's not throwing any errors, so I'm at a loss.

All I end up getting is a blank white page.

The function main() is not gonna call itself. When you declare a function, you have to make sure you execute it, otherwise it'll just sit there, unused.

// First we declare the function
function main() {
    // Do a bunch of stuff
}

// Then we call the function
main();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM