What is the process of adding a unique model to three.js?

Despite trying numerous solutions to a common problem, I am still unable to import my 3D model in Three.js using the following code:

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/GLTFLoader.js"></script>
<!-- <script src="js/3d.js"></script> -->
<script>
    
    /**
 * Base
 */
// Canvas
const canvas = document.querySelector('canvas.webgl')

// Scene
const scene = new THREE.Scene()

//Material
const material = new THREE.MeshToonMaterial({ color: '#ffeded'})

/**
 * Object Meshes
 */


const mesh1 = new THREE.Mesh(
    new THREE.TorusGeometry(1, 0.4, 16, 60),
    material
)
const mesh2 = new THREE.Mesh(
    new THREE.ConeGeometry(1, 2, 32),
    material
)
const mesh3 = new THREE.Mesh(
    new THREE.TorusKnotGeometry(0.8, 0.35, 100, 16),
    material
)

scene.add(mesh1,mesh2, mesh3)

function loadGLTF() {
    let gbLoader = new THREE.GLTFLoader();

    gbLoader.load('GB.gltf', (gltf) => {
        // gbMesh.scale.set(0.1, 0.1, 0.1);
        scene.add(gltf.scene);
    });
}



/**
 * Sizes
 */
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () =>
{
    // Update sizes
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight

    // Update camera
    camera.aspect = sizes.width / sizes.height
    camera.updateProjectionMatrix()

    // Update renderer
    renderer.setSize(sizes.width, sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

// Position

const objectsDistance = 4

mesh1.position.y = - objectsDistance * 0
mesh2.position.y = - objectsDistance * 1
mesh3.position.y = - objectsDistance * 2


const sectionMeshes = [ mesh1, mesh2, mesh3 ]

/**
 * Camera
 */
// Base camera
const camera = new THREE.PerspectiveCamera(35, sizes.width / sizes.height, 0.1, 100)
camera.position.z = 100
scene.add(camera)

/**
 * Lights
 */
 const directionalLight = new THREE.DirectionalLight('#ffffff', 1)
 directionalLight.position.set(1, 1, 0)
 scene.add(directionalLight)

 /**
 * Scroll
 */
let scrollY = window.scrollY

window.addEventListener('scroll', () =>
{
    scrollY = window.scrollY
})

/**
 * Renderer
 */
const renderer = new THREE.WebGLRenderer({
    canvas: canvas,
    alpha: true
})
renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

/**
 * Animate
 */
const clock = new THREE.Clock()

const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()

    // Animate camera
    camera.position.y = - scrollY / sizes.height * objectsDistance

    // Animate meshes
    for(const mesh of sectionMeshes)
    {
        mesh.rotation.x = elapsedTime * 0.1
        mesh.rotation.y = elapsedTime * 0.12
    }

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()

</script>

<script>
 AOS.init({
     once: true,
 });
</script>

While everything else is functioning correctly, unfortunately, my 3D model does not appear on the screen as expected.

Here are the results of running the code in my browser

I have placed my .gltf file in the same directory as my javascript file and I am using a MAMP server to run the code. Any assistance would be greatly appreciated.

Could someone please provide a solution?

Answer №1

The loadGLTF() function contains your loading code, but it seems that you forgot to actually call the function.

To fix this issue, make sure to either call the loadGLTF function before calling tick(), or move the loading code outside of the loadGLTF function.

Answer №2

You have created the loadGLTF() function but it is not being called anywhere in your code. To use it, consider calling it just before the tick() function:


loadGLTF()
const tick = () =>
{

If you need help getting started with loading a helmet.gltf, you can refer to this example on GitHub. Additionally, you can check out a live example for a demonstration.

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

Customize the default directory for local node modules installation in node.js using npm

If I prefer not to have my local (per project) packages installed in the node_modules directory, but rather in a directory named sources/node_modules, is there a way to override this like you can with bower? In bower, you specify the location using a .bow ...

What is the quickest way to find and add together the two smallest numbers from a given array of numbers using JavaScript?

const getSumOfTwoSmallestNumbers = (numbers) => { const sortedNumbers = numbers.sort((a, b) => a - b); return sortedNumbers[0] + sortedNumbers[1]; } I encountered this challenge on Code Wars. My function to find the sum of the two smallest num ...

Tips for retrieving the text from a child element in a list with jQuery

I'm having trouble accessing the text of a child element within a list. I can only access the parent element and not sure how to get to the child element. Here is the HTML code: <ul class="nav nav-list"> <li class="active"> < ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

Allowing a certain amount of time to pass before executing a method

I'm familiar with using setTimeout and setInterval to delay the execution of a method, but I am facing a specific issue. I am working on implementing a card game where three CPU players take turns with a 500ms delay between each turn. Below is the cod ...

Using Vue.js to detect changes in a value and dynamically highlight the text

I am working on a simple script that generates random numbers every few moments. I want to change the background color whenever the random number is not equal to the one before it. Is this possible? For example, if the random numbers generated are 1, 1, an ...

Tips for getting the setInterval function to work with a progress bar even when a tab is not in focus

After browsing through similar questions, I couldn't find the answer I was looking for. As a newbie in programming experimenting with JavaScript Progress Bar, I encountered an issue where the progress bar would pause and the counter wouldn't coun ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

Struggling to successfully pass data between pages using JSON

I'm currently working on HTML code for a view cart page where I display an item name. My goal is to be able to transfer this data, along with others later on, to a different HTML page that will automatically generate a list of multiple items with pric ...

Can the repeated use of AJAX function calls at regular intervals adversely affect the speed of the application?

On a specific page of my application, I have been using an AJAX function continuously as shown below: <script type="text/javascript"> $(document).ready(function(){ setInterval(function() { $.ajax({ ...

activating a jQuery function and sending a parameter

Looking for some help with JavaScript - I'm having trouble getting this code to work. I need to trigger a predefined function from one script within my AJAX script. Specifically, I want to activate the qtip functionality on the content of a div that i ...

Guide to dynamically loading a component using a variable name in Vue.js?

Is it possible to dynamically load a component in a vue.js application using a variable name? For example, if I have the following component registered: <template id="goal"> <h1>Goal:{{data.text}}</h1> </template> Instead of di ...

Nunjucks not loading the script when moving from one page to another

Currently, I am in the process of developing a website utilizing nunjucks and express. This website serves as a blog platform with content sourced from prismic. My goal is to load a script file for an active campaign form whenever a user navigates from a b ...

Create eye-catching banners, images, iframes, and more!

I am the owner of a PHP MySQL website and I'm looking to offer users banners and images that they can display on their own websites or forums. Similar to Facebook's feature, I want to allow users to use dynamic banners with links. This means the ...

I'm all set to launch my express js application! What are the major security concerns that I need to keep in

As a beginner in deploying express applications, I find myself lacking in knowledge about the essential security measures that need to be taken before launching a web application. Here are some key points regarding my website: 1) It is a simple website ...

Issue: tanstack_react_query's useQuery function is not recognized

Error: (0 , tanstack_react_query__WEBPACK_IMPORTED_MODULE_3_.useQuery) is not a function While implementing data fetching in my Next.js project using @tanstack/react-query, I encountered the above error message. Below is the code snippet where the issue ...

The Redux Toolkit Slice Reducer fails to function properly when incorporating an extra Reducer that is not compatible

I am relatively new to the world of Redux and have been attempting to use RTK right from the start. It has been quite a challenging and confusing experience for me so far. Recently, I decided to include a standard Reducer instead of an extraReducer in my ...

Troubleshooting issues with environment variables in Next.js version 12.2.2

I tried following the steps outlined in the official documentation, but I'm encountering an issue. Here is what I did: next.config.js const nextConfig = { reactStrictMode: true, swcMinify: true, env : { MORALIS_ID: 'moralisId', ...

Numerous attributes for displaying ngOption values

I have an item that resembles the following: $scope.team = [ { name: "John", number: 1 }, { name: "Emma", number: 2 } ]; Currently, in my HTML code, I am using ngOption to populate a dropdown menu with values from the object. < ...

What is the process for including a new item in a JavaScript dictionary?

I'm currently learning JavaScript and I've encountered a challenge. I have a dictionary that I'd like to update whenever a button is clicked and the user enters some data in a prompt. However, for some reason, I am unable to successfully upd ...