The GLTF loader in Three Js isn't displaying my model

Attempting to incorporate a 3D heart model into Three.js and attach an image to the front of the heart seems to be causing problems. Even without adding the image, the heart doesn't appear in the scene. As a newcomer to Three.js, it's possible that I'm approaching this incorrectly, but I've tried using code directly from the documentation with no success. Oddly enough, there are no error messages being displayed, and I can see the AxesHelper. Additionally, when loading in a cube, everything works as expected, indicating that the issue might lie specifically with the heart model.

function handleHeart(img) {
        document.getElementById("divRight").innerHTML = ""
        let renderer = new THREE.WebGLRenderer();
        document.getElementById("divRight").appendChild(renderer.domElement);
        let w = document.getElementById("divRight").clientWidth
        let h = 600
        renderer.setSize( w, h)
        let camera = new THREE.PerspectiveCamera(35, w / h, 0.1, 3000 );
        const controls = new THREE.OrbitControls( camera, renderer.domElement );
        camera.position.set( 0, 0, 10 );
        camera.lookAt(new THREE.Vector3(0, 0, 0))
        controls.update();
        let scene = new THREE.Scene();
        scene.background = new THREE.Color( 'grey' );
        light = new THREE.AmbientLight(0xffffff); 
        scene.add(light);

       
            

        const loader = new THREE.GLTFLoader();

        loader.load(
            // resource URL
            'models/heart_v1.glb',
            // called when the resource is loaded
            function ( gltf ) {

                let material = new THREE.MeshBasicMaterial( { map: img } );
        
                let model = gltf.scene || gltf.scenes[0];
                //model.scale.set(1000,1000,1000)
                model.material = material
                scene.add(model)
                model.position.z = -10
                
        
            },
            // called while loading is progressing
            function ( xhr ) {
        
                console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
        
            },
            // called when loading has errors
            function ( error ) {
                console.log(error)
                console.log( 'An error happened' );
        
            })

        scene.add(new THREE.AxesHelper(100))
        renderer.render(scene, camera)
    }

Explore the code on Replit here: https://repl.it/@AlecStein44/Threejs-help#javascript.js

Answer №1

model.material = material

The code above needs correction. The correct way to assign the material is by using the following code snippet:

model.traverse( function( object ) {

    if ( object.isMesh ) object.material = material;

} );

Please note that even after correcting this issue, adding a texture will not work as expected because your model heart_v1.glb does not have any texture coordinates defined.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic JavaScript Total Calculation

I have been struggling to update the total price for specific options. Even though the code was created by someone else and has worked fine for many users, I can't seem to make it work correctly. Any assistance would be greatly appreciated. Here is t ...

What is the best way to load an index.js file within a plugin framework?

I currently have an isolated index.js file located at plugins/some_plugin/index.js After attempting to run require(path_to_index.js) in my application, I encounter a 'cannot find modules' error message. This issue is understandable as the "some ...

The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. T ...

Exploring the ng-repeat directive with an array of objects

In the server response, I have an array of objects that I am trying to iterate over using ng-repeat in order to read each value. While trying to use array[0].value works fine, things are not going as expected when using ng-repeat. Despite all my efforts ...

I'm struggling to understand the purpose of using response.on

I have a code snippet here and I am curious about the functionality of "response.on" and why we are passing "data". What does this "data" represent? Also, could you explain what ".on" is specifically used for in this context? const express = require("exp ...

Utilizing a background image property within a styled component - Exploring with Typescript and Next.js

How do I implement a `backgroung-image` passed as a `prop` in a styled component on a Typescript/Next.js project? I attempted it in styled.ts type Props = { img?: string } export const Wrapper = styled.div<Props>` width: 300px; height: 300px; ...

Creating a single page application in Angular2+ using JSON data

I am looking to create an Angular JS application using the provided JSON structure: { name: 'App Name', pages: [ { name: 'Home', url: '/', layout: { type:'HTMLElement' tag:'div ...

Enhancing JavaScript Asynchronous Programming with EventLoop and async/await

Exploring the intricacies of how JavaScript processes asynchronous methods led me to dive into async/await. In an effort to gain a complete understanding, I crafted the following example: async function first() { console.log(9); await Promise.resolv ...

Guide to organizing a one-to-one object map within Angular JS ng-repeat

Is there a way to organize a one-to-one object map in angular.js using filters (or any other technique) while working within an ng-repeat loop? This is what I currently have: obj:{ a:3, c:5, d:1, g:15 } Basically, I want to achieve s ...

What could be causing the issue with setting a value for a JSON array in the following method?

Consider this piece of code that I'm currently working with: compareList[productName] = productID + ',' + productHref; console.log(productName + ' ' + productID + ' ' + productHref + ' ' + compareList.length); ...

Achieving functionality with dropdown menus in jQuery

I am facing an issue with a dropdown menu that works perfectly in jsFiddle during testing, but does not function as expected when I run it on my testing server. jsFiddle: http://jsfiddle.net/cyberjo50/39bu8/2/ HTML <!doctype html> <html> < ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

Unable to reset HighCharts Speedometer value to zero

I am currently experimenting with implementing the highcharts speedometer. The goal is to simulate a connection meter - when there is a good connection, the meter should display values between 30 and 100. If the connection result from an Ajax call is any ...

Features for React Calculator

I have been developing a React Calculator that includes a display for history and output, along with buttons for numbers and operators. I was successful in rendering the initial structure. For my next task, I aim to update the display with the pressed num ...

In what way can a container impact the appearance of a child placed in the default slots?

Visiting the vue playground. The main goal is for the container component to have control over an unspecified number of child components in the default slot. In order to achieve this, it's assumed that each child component must either hold a propert ...

Tips for creating an expression within ng-if

I am struggling with placing an expression inside ng-if that needs to be assessed in order for my content to be shown based on its outcome. This is what I currently have: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image< ...

Issue with triggering ReactJS onClick function accurately

For the function to work correctly, I had to add e.preventDefault(). However, my goal is for it to redirect the user to '/' after submitting the form. Below is the function that I am attempting to trigger: onAddPoints = (e) => { e.prevent ...

Creating a dynamic cascading dropdown list with Vue.js: Step-by-step guide

I successfully implemented a dropdown list using Vue.js, but now I want to add another similar list. How can I set this up? Here are the codes for both dropdown lists: var addUserVue = new Vue({ el: "#app", data: { heading: "Vue Select Cas ...

Is there an issue with my JavaScript append method?

Within the following method, an object named o gets appended to a list of objects called qs. The section that is commented out seems to be causing issues, while the uncommented section is functional. What could possibly be wrong with the commented part? on ...

What is the mechanism by which the callback methods of the $http service inform Angular of a change in the model?

Consider the AngularJS controller provided below: function PhoneListCtrl($scope, $http) { $scope.phones = {}; $http.get('phones/phones.json').success(function(data) { $scope.phones = data.splice(0, 5); }); $scope.orderProp = ...