Three.js导入3D模型

时间:2020-06-22 15:56:54

标签: javascript html three.js aframe

我遵循了一些教程来导入3d模型。我已经成功使用A-Frame标签导入了,但是当我尝试使用Three.js进行导入时,它无法正常工作。我已经从youtube上找到的教程中复制并粘贴了以下代码。 https://www.youtube.com/watch?v=1TeMXIWRrqE

<!DOCTYPE html>
<html>
  <head>
    <meta charset=UTF-8 />
    <link rel="stylesheet" type="text/css" href="main.css" />
  </head>
  <body>
    <script src="three.js"></script>
    <script src="GLTFLoader.js"></script>
    <script src="OrbitControls.js"></script>
    <script>
      let scene, camera, renderer;
      function init() {
        scene = new THREE.Scene();
        scene.background = new THREE.Color(0xdddddd);
        camera = new THREE.PerspectiveCamera(40,window.innerWidth/window.innerHeight,1,5000);
        camera.rotation.y = 45/180*Math.PI;
        camera.position.x = 800;
        camera.position.y = 100;
        camera.position.z = 1000;

        controls = new THREE.OrbitControls(camera);
        controls.addEventListener('change', renderer);

        hlight = new THREE.AmbientLight (0x404040,100);
        scene.add(hlight);

        directionalLight = new THREE.DirectionalLight(0xffffff,100);
        directionalLight.position.set(0,1,0);
        directionalLight.castShadow = true;
        scene.add(directionalLight);
        light = new THREE.PointLight(0xc4c4c4,10);
        light.position.set(0,300,500);
        scene.add(light);
        light2 = new THREE.PointLight(0xc4c4c4,10);
        light2.position.set(500,100,0);
        scene.add(light2);
        light3 = new THREE.PointLight(0xc4c4c4,10);
        light3.position.set(0,100,-500);
        scene.add(light3);
        light4 = new THREE.PointLight(0xc4c4c4,10);
        light4.position.set(-500,300,500);
        scene.add(light4);
        renderer = new THREE.WebGLRenderer({antialias:true});
        renderer.setSize(window.innerWidth,window.innerHeight);
        document.body.appendChild(renderer.domElement);
        
        let loader = new THREE.GLTFLoader();
        loader.load('Model/scene.gltf', function(gltf){
          car = gltf.scene.children[0];
          car.scale.set(0.5,0.5,0.5);
          scene.add(gltf.scene);
          animate();
          
        });
      }
      function animate() {
        renderer.render(scene,camera);
        requestAnimationFrame(animate);
      
      }
      init();
    </script>
  </body>
</html>

它给我的错误...

    at new THREE.OrbitControls (OrbitControls.js:1101)
    at init (index.html:22)
    at index.html:62

谢谢。

1 个答案:

答案 0 :(得分:1)

启动new THREE.OrbitControls();时缺少参数。期望cameraHTMLElement,但是您只是通过摄影机。 See the docs here。您可以通过添加渲染器的画布来修复它:

renderer = new THREE.WebGLRenderer({antialias:true});
document.body.appendChild(renderer.domElement);
controls = new THREE.OrbitControls(camera, renderer.domElement);