bingandabong
bingandabong

Reputation: 13

How do I load a 3D model using three.js using the editor playcode.io?

I have been trying to load in a 3d Model on playcode.io. My browser supports WebGl and so does playcode.io (I think) So far, no success. There is no problem The model either. The model is called plane.gltf. The screen is just a blank black screen. Here is my code for the three.js:

import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

const loader = new GLTFLoader();

loader.load( 'plane.gltf', function ( gltf ) {

    scene.add( gltf.scene );

}, undefined, function ( error ) {

    console.error( error );

} );

function animate() {
    renderer.render( scene, camera );
}
renderer.setAnimationLoop( animate );

And here is my code for the HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>My first three.js app</title>
        <style>
            body { margin: 0; }
        </style>
    </head>
    <body>
        <script type="module" src="/main.js"></script>
    </body>
</html>

I checked all the threeJS documentation and tutorials. I was expecting the model to load up. it didn't. I tried in multiple editors but no success. am I doing something wrong?

Upvotes: 0

Views: 98

Answers (1)

Łukasz Daniel Mastalerz
Łukasz Daniel Mastalerz

Reputation: 2217

The black screen tells you that you are rendering the scene correctly. Assuming the path to the model is correct. First, add lights to the scene:

const light = new THREE.DirectionalLight(0xffffff, .5);
scene.add(light1);
const light2 = new THREE.AmbientLight(0xffffff);
scene.add(light2);

When you still see black screen, that probably means that model is in wrong place on scene.

Try set:

camera.position.z = 10; // Make some experiments with position

That depends on your model sometimes is to big, no need to experiments with scale, just move camera.

If still you render black screen try load model from link, to be sure, that something else produces that issue.

const loader = new GLTFLoader();
loader.load(
   'https://threejs.org/examples/models/gltf/Nefertiti/Nefertiti.glb',
    function (gltf) {
        scene.add(gltf.scene);
    });

Upvotes: 0

Related Questions