在我的场景中,我有2个网格属性。其中一个是创建的,另一个来自stl
文件。当我加载页面时,只有我创建的网格才可见。 stl
文件中的下一个文件根本没有显示。
据我所知,加载文件并呈现mesh
需要时间。为了解决这个问题,我添加了一个setTimeout
函数。效果很好。
但是在加载renderer
之后调用mesh
函数的正确方法是什么?
示例:在jQuery中我使用$when().done()
- 如何处理?
我的代码:
$(function () {
var scene, camera, renderer;
var init = function () {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera (45, window.innerWidth / window.innerHeight, 0.1, 1000 );
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xEEEEEE);
var axes = new THREE.AxisHelper(20);
scene.add(axes);
var cubeGeometry = new THREE.BoxGeometry(4, 4, 4)
var cubeMaterial = new THREE.MeshBasicMaterial({color: 0xff0000});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.x = -4;
cube.position.y = 3;
cube.position.z = 0;
scene.add(cube);
camera.position.x = -30;
camera.position.y = 40;
camera.position.z = 30;
camera.lookAt(scene.position);
var loader = new THREE.STLLoader();
loader.load('stl/model.stl', function ( geometry ) {
var material = new THREE.MeshPhongMaterial( { color: 0xffffff } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.set( 0, - 0.25, 0.6 );
mesh.rotation.set( 0, - Math.PI / 2, 0 );
mesh.scale.set( 0.5, 0.5, 0.5 );
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add( mesh );
} );
setTimeout(function () {
$('#webGL').append(renderer.domElement);
renderer.render(scene, camera)
}, 100)
}
function render () {
}
init();
})
答案 0 :(得分:1)
您正在使用的一种正确方法是回调函数。 当加载器加载模型时执行回调,只需将渲染器调用添加到它:
loader.load('stl/model.stl', function ( geometry ) {
// this is the callback function
// do some stuff with your model
scene.add( mesh );
renderer.render( scene, camera );
} );
在three.js中还有Loading Manager,请参阅我在这里预加载OBJ + MTL的其他帖子:Preloading Obj+Mtl Objects in Three.js。
加载经理:
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
// this gets called after an object has been loaded
};
manager.onLoad = function () {
// everything is loaded
renderer.render( scene, camera );
};
var loader = new THREE.STLLoader( manager );
loader.load('stl/model.stl', function ( geometry ) {
var material = new THREE.MeshPhongMaterial( { color: 0xffffff } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.set( 0, - 0.25, 0.6 );
mesh.rotation.set( 0, - Math.PI / 2, 0 );
mesh.scale.set( 0.5, 0.5, 0.5 );
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add( mesh );
} );