I need your help. I'm trying to add my model to a canvas I've added to the html-document. But the following code doesn't work:
function main() {
const container = document.querySelector( "#machine-model" );
let height = container.offsetHeight; // Offset height = element + padding + border + scrollbar
let width = container.offsetWidth;
const fov = 75;
const aspect = width / height;
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
camera.position.x = 8.3;
camera.position.y = 11.7;
camera.position.z = -8;
camera.lookAt( new THREE.Vector3( 0, 0, 0 ) );
const scene = new THREE.Scene();
scene.background = new THREE.Color( 0xFFFFFF ); // changes background color from black to white
const ambiLight = new THREE.AmbientLight( 0xFFFFFF, 0.5 );
scene.add( ambiLight );
const spotLight = new THREE.SpotLight( 0xFFFFFF, 0.6 );
spotLight.position.set( 13.6, 20.1, -13.9 );
spotLight.castShadow = true;
scene.add( spotLight );
const gltfLoader = new THREE.GLTFLoader();
gltfLoader.load( "model/model.glb", function( gltf ) {
const model = gltf.scene;
model.rotateX( -Math.PI/2 );
console.log( model );
scene.add( model );
});
const renderer = new THREE.WebGLRenderer( { canvas: container, antialias: true, alpha: true } ); // alpha = true -> alpha = 0
renderer.setSize( width, height );
function render() {
renderer.render( scene, camera );
requestAnimationFrame( render );
}
requestAnimationFrame( render );
};
main();
Here's a link to working JSFiddle demo
If I add the id of my canvas to the canvas parameter of the renderer, I don't need to do it with appendChild, right?
Based on your fiddle, the canvas seems to be passed successfully. The problem instead seems to be your far
distance, which you set to 5, even though you place your camera quite far away from the origin.
Try instead with a larger far
value, say 1000.