Hello dear friends,
I’m very new on this, I’m loading a GLB file with Three.js, so far so good, the problem is I haven’t been able to load the object in the position I want, the object should load like in the center of the view.
My actual code is:
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.154.0/build/three.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'https://unpkg.com/three@0.154.0/examples/jsm/loaders/GLTFLoader.js';
import { OrbitControls } from 'https://unpkg.com/three@0.154.0/examples/jsm/controls/OrbitControls.js';
var glbContainer = document.querySelector('.glb-container')
// Creating scene
const scene = new THREE.Scene()
scene.background = new THREE.Color( 'red');
//Creating Grid
const gridHelper = new THREE.GridHelper( 20, 20 );
scene.add( gridHelper );
// Setting sizes
const sizes = {
width: glbContainer.clientWidth,
height: glbContainer.clientHeight,
}
// Creating render
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
})
glbContainer.appendChild(renderer.domElement)
renderer.setSize(sizes.width, sizes.height)
// Creating camera
const camera = new THREE.PerspectiveCamera(20, sizes.width / sizes.height, 1, 100)
camera.position.set(0, 0, 50);
scene.add(camera)
//Creating Controls
const controls = new OrbitControls( camera, renderer.domElement )
controls.enableZoom = false;
//controls.enablePan = false;
// Import GLB
const loader = new GLTFLoader();
gui.domElement.id = 'gui';
// Load a glTF resource
loader.load(
// resource URL
'../assets/glb/simcard.glb',
// called when the resource is loaded
function ( gltf ) {
scene.add( gltf.scene );
gltf.scene.scale.set(280, 280, 280);
gltf.scene.position.set(0, 0, 0);
},
// called while loading is progressing
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
);
function animate() {
requestAnimationFrame(animate)
controls.update()
renderer.render(scene, camera)
}
animate()
</script>
And the 3D model is loading like this:
Notes
- Red background set to appreciate the limits of the view.
- Light removed for example purposes.
With the “Pan” option of OrbitControls I’ve moved the grid down in order to achieve the desired position which is more or less the following:
I haven’t been able to load the object in this position by default.
I’ve tried to modify the camera position in its Y coordinate, but I obtain like a high-angle shot of the object.
I’ve modified the “gltf.scene.position” making the model to move down BUT it goes through the grid, which is not a good practice I think.
Can some body give me a hand please? I really appreciate any help you can provide.