Display an item using Three.js

Greetings! I am looking to display an object using three.js without the need for a webcam or marker. Just a simple blank background with the object is all I require. I attempted to extract some code from the damaged helmet example, but unfortunately, it has not been successful so far. Any help would be greatly appreciated!

Here is the current code snippet that I am working with:

function start(){

    var renderer = new THREE.WebGLRenderer({
        antialias : true,
        alpha: true
    });
    
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.domElement.style.position = 'absolute'
    renderer.domElement.style.top = '0px'
    renderer.domElement.style.left = '0px'
    document.body.appendChild( renderer.domElement );

    var onRenderFcts = [];
   
    var scene = new THREE.Scene();

    var camera = new THREE.Camera();
    scene.add(camera);

    var light = new THREE.DirectionalLight(0xffffff, 1);
    light.position.set(0, 0, 1);
    scene.add(light);


    var loader = new THREE.OBJLoader();

    var mtlLoader = new THREE.MTLLoader();

    mtlLoader.load( "3d_models/OBJ/ano/ano.mtl", function( materials ) {
        materials.preload();
        var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials( materials );
        objLoader.load("3d_models/OBJ/ano/ano.obj", function ( object ) {
            object.rotation.set(-Math.PI/2,0,0);
            console.log(object.children[0])
            scene.add( object );
        });
    },
    function ( xhr ) {
        console.log( 'OBJ ' + ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
    },
    function ( error ) {
        console.log(error);
    });

}

Answer №1

Ensure that you properly position your camera to prevent it from being obscured by objects.

In addition, without viewing the entirety of your code, it is unclear where you are initiating the "start()" function from.

Answer №2

Below is a code snippet I came across in a Three.js example. I made some modifications to simplify it:

var renderer;
        var clock = new THREE.Clock();
        var mixers = [];
        var onRenderFcts = [];
        var camera2, scene2;
        init2();

        function init2() {
            var container, stats;

            container = document.createElement( 'div' );
            document.body.appendChild( container );
            camera2 = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
            camera2.position.z = 250;

            scene2 = new THREE.Scene();
            var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
            scene2.add( ambientLight );
            var pointLight = new THREE.PointLight( 0xffffff, 0.8 );
            camera2.add( pointLight );
            scene2.add( camera2 );

            var loader = new THREE.OBJLoader();

            var mtlLoader = new THREE.MTLLoader();

            mtlLoader.load( "3d_models/OBJ/ano/ano.mtl", function( materials ) {
                materials.preload();
                console.log(materials);
                var objLoader = new THREE.OBJLoader();
                objLoader.setMaterials( materials );
                objLoader.load("3d_models/OBJ/ano/ano.obj", function ( object ) {
                    console.log(object.children[0])
                    scene2.add( object );
                    onRenderFcts.push(function(){
                                object.rotation.y += 0.03;
                    })
                });
            },
            function ( xhr ) {
                console.log( 'OBJ ' + ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
            },
            function ( error ) {
                console.log(error);
            });
            renderer = new THREE.WebGLRenderer();
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            container.appendChild( renderer.domElement );
        }

        onRenderFcts.push(function(){
                renderer.render( scene2, camera2 );
            })
        // run the rendering loop
        var lastTimeMsec= null
        requestAnimationFrame(function animate(nowMsec){
            // keep looping
            requestAnimationFrame( animate );
            if ( mixers.length > 0 ) {
                for ( var i = 0; i < mixers.length; i ++ ) {
                    mixers[ i ].update( clock.getDelta() );
                }
            }
            // measure time
            lastTimeMsec    = lastTimeMsec || nowMsec-1000/60
            var deltaMsec   = Math.min(200, nowMsec - lastTimeMsec)
            lastTimeMsec    = nowMsec
            // call each update function
            onRenderFcts.forEach(function(onRenderFct){

                onRenderFct(deltaMsec/1000, nowMsec/1000)
            })
        })

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

Tips for sending the key property of a rendered list in React to a function using a different HTML tag

Is there a way to pass the Key value of each list item through the button created inside the li tag to a function for filtering out that element and rendering a new list? I need assistance with completing the handleDelete function. import { useState } fr ...

Searching for the regulations on type-casting in JavaScript

Seeking a definitive set of guidelines regarding automatic typecasting and when it occurs. I am in the process of developing some rules for new developers, an example being: 90 > '100' // comparison as integers '90' > 100 // ...

Sort through a JavaScript array based on an object that holds a limited number of the array's properties

Is there a way to efficiently find matching items in an array of objects using a filter object that only includes a subset of the array properties? For instance, consider a customer: let Customer = { Name: "John Doe", Age: 80, Hair: "Red", ...

The absence of parameters in the Express.js middleware object

const application = express(); let routerInstance = require('express').Router({mergeParams: true}); const payloadMiddlewareFunction = (request, response, next) => { console.log('A:', request.params); const {params, query} = reque ...

Tips on modifying a particular item within a sub-document array using Mongoose?

Working on my node.js and mongoose project, I have a main Schema and a sub-Schema set up. const childrenSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, hobbies: [String] }) const parentSchema = new mongoose.Schema({ ...

Is it possible for me to generate a modal with a unique id that changes dynamically?

I have been experimenting with creating a modal window that dynamically opens based on generated PHP ids stored in a database. These ids are utilized to populate a user table when necessary. My goal is to click on a user and have their settings and option ...

The Javascript Navbar is malfunctioning on Firefox

Currently, I am working on a horizontal menu that includes submenus. My goal is to use Javascript to display the submenu when a user hovers over the parent menu. I created a JSFiddle example, which seems to be experiencing issues in FireFox! However, it w ...

Generate a Jade/Pug template using a JavaScript variable

I've been encountering some difficulties with Pug (Jade) recently. I'm passing an array from the backend to the frontend and then sorting it on the client side. Here's how it looks: potentials is the array of objects that I'm sending ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...

Creating a dynamic navigation menu in Angularjs using UI-Bootstrap tabs and UI-Router for seamless user

When working on this Plunker, I encountered an issue with the functionality of menu links and tabs. The problem arises when trying to navigate between 'Route 1' and 'Route 2'. Clicking twice on 'Route 1' doesn't properly ...

How to handle typeahead events in the right sequence using jQuery AJAX?

I'm currently developing a web application using HTML, jQuery, and a Java REST-service backend. One of the features I have implemented is a textfield with typeahead suggestions, which triggers a server-round trip every time the user enters a character ...

Floating sidebar dynamically overlaps with the footer as you scroll

Currently, I am utilizing Bootstrap for my website layout and facing an issue with making the sidebar fixed on scroll after it reaches a certain point in the viewport. The scrolling functionality works fine initially, but when it reaches the bottom, the si ...

Transitioning from jQuery to AngularJS functions

I'm new to writing a jQuery function within AngularJs and could use some guidance. Any suggestions on the best approach for achieving this? Appreciate it! $(function() { $('.input input').focus(function() { $(this).parent('.in ...

What is the best way to apply a CSS class to a div element without affecting its child elements using JavaScript?

Currently, I am using JavaScript to add and remove a CSS class through a click event. Within my div structure, I have multiple similar divs. While I can successfully add and remove the class from my main div, I am facing an issue where the class is also ap ...

Adding TH into a TABLE in Angular 2 by verifying TD elements

I am seeking a way to automatically generate thead and th, using td in the template : <Datatable> <tr #lineSelected *ngFor="let subscription of results"> <td nameColumn="Nom">{{subscription.name}}</td> <td n ...

"The alert() function in Javascript takes precedence over the code that came before it

When I have a contact form with a submit button, my goal is to use JQuery to change the button text to "Send" and display the received response in an alert, once a response is received from the server-side PHP processing the submitted data. Change button ...

Tips for accessing the property 'checked' within a named function called change()

After successfully implementing a code that checks if the property value is true or false, I decided to turn it into a named function for reusability. However, I encountered an issue where the new function always returns False. var $artistip = null; var ...

How to choose the desired day within a specific month when creating a calendar from scratch?

Hi there! I need some assistance. I'm currently working on enhancing a calendar by adding an extra feature. The idea is that when the user selects one or more days, those specific day(s) should be highlighted. However, I'm facing an issue where s ...

Starting a checkbox group with values based on total number

I am facing a challenge with a group of checkboxes that have values assigned as 1,2,4,8,16,32,64. Each number corresponds to a day of the week (e.g. Sunday, Monday etc...) The total value of the checkbox group is calculated as the sum of the selected chec ...

How to create select options in Angular.js without using the ng-option directive

I receive a JSON object from a service and I am using some of its fields to populate my select option list. However, when I try to print the selected value in my controller, the output response is "undefined". Can someone help me figure out what I'm ...