繁体   English   中英

无法使用three.js渲染GLTF对象

[英]Unable to render GLTF object with three.js

我正在尝试渲染three.js指南( https://github.com/mrdoob/three.js/blob/master/examples/models/gltf/DamagedHelmet )提供的GLTF对象

为此,我尝试使用他们指南中提供的以下加载程序( https://threejs.org/docs/#examples/en/loaders/GLTFLoader

按照threejs指南,我编写了这段代码来加载和呈现一个GLTF文件:

"use strict";
const loader = new THREE.GLTFLoader();
const scene = new THREE.Scene();
const ratio = window.innerWidth / window.innerHeight
const camera = new THREE.PerspectiveCamera( 75, ratio, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();


const path = 'https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf'

camera.position.set(0,0,0)
camera.lookAt(10,0,0)
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

renderer.render( scene, camera );


loader.load(path, function ( gltf ) {
  gltf.scene.position.x=10
  scene.add( gltf.scene );
}, function ( xhr ) {
  console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
 
}, function ( error ) {
  console.log( 'An error happened' , path);
});

不幸的是,即使浏览器从 Internet 正确加载了资源文件并且控制台中没有错误,场景仍然是黑色的。

所以,我的问题是:如何修复我的 codepen 以便它使用 Three.js 在浏览器中显示 GLTF 对象?

编辑:感谢最佳答案,这里有一个工作正常的代码笔: https ://codepen.io/spocchio/pen/vYJpaLg

我注意到两个问题:

  1. 你的场景需要灯光。 当网格被添加到场景中时,它们不会被照亮,因此它们保持黑色。
  2. 您只调用renderer.render()一次,这发生您加载 GLTF之前 因此,当头盔最终加载时,不会进行渲染。

我在你的 Codepen 中做了这两个更新,头盔出现了。

renderer.render( scene, camera );

// Add ambient light
scene.add(new THREE.AmbientLight());

loader.load(path, function ( gltf ) {
  gltf.scene.position.x=10
  scene.add( gltf.scene );

  // Render scene after assets have been added
  renderer.render( scene, camera );
}, function ( xhr ) {
  console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
 
}, function ( error ) {
  console.log( 'An error happened' , path);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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