Having trouble with the Three.js OBJ loader in CodePen?

Currently, I am experiencing a challenge with loading an OBJ file on Three.js. Oddly enough, the functionality seems to be working perfectly fine when I deploy the files on my server as demonstrated here:

However, when attempting to run it on Codepen, I encounter issues like so: http://codepen.io/hafsadanguir/pen/RaJaPZ

var container;
        var camera, scene, renderer;
        var mouseX = 0, mouseY = 0;
        var windowHalfX = window.innerWidth/ 2;
        var windowHalfY = window.innerHeight / 2;
        init();
        animate();

        function init() {
            container = document.createElement( 'div' );
            document.body.appendChild( container );
            camera = new THREE.PerspectiveCamera( 20, window.innerWidth / window.innerHeight, 1, 10000 );
                            camera.position.z = 900;
                            camera.position.x = -1000;
            // scene
            scene = new THREE.Scene();
            var ambient = new THREE.AmbientLight( 0x404040 ); //This creates an Ambientlight with a color.
            scene.add( ambient );

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

            // texture
            var manager = new THREE.LoadingManager();
            manager.onProgress = function ( item, loaded, total ) {
                console.log( item, loaded, total );
            };
            var texture = new THREE.Texture();
            var onProgress = function ( xhr ) {
                if ( xhr.lengthComputable ) {
                    var percentComplete = xhr.loaded / xhr.total * 100;
                    console.log( Math.round(percentComplete, 2) + '% downloaded' );
                }
            };
            var onError = function ( xhr ) {
            };
            var loader = new THREE.ImageLoader( manager );
            loader.load('http://hafsadanguir.com/THREEJS/textures/red.jpg', function ( image ) {
                texture.image = image;
                texture.needsUpdate = true;
            } );

            // model
            var loader = new THREE.OBJLoader( manager );
            loader.load('http://hafsadanguir.com/THREEJS/obj/Heart.obj', function ( object ) {
                object.traverse( function ( child ) {
                    if ( child instanceof THREE.Mesh ) {
                        child.material.map = texture;
                    }
                } );
                object.position.y = -150;

                scene.add( object );
            }, onProgress, onError );
            //
            renderer = new THREE.WebGLRenderer();
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            container.appendChild( renderer.domElement );
            document.addEventListener( 'mousemove', onDocumentMouseMove, false );
            //
            window.addEventListener( 'resize', onWindowResize, false );
        }
        function onWindowResize() {
            windowHalfX = window.innerWidth / 2;
            windowHalfY = window.innerHeight / 2;
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize( window.innerWidth, window.innerHeight );

        }
        function onDocumentMouseMove( event ) {
            mouseX = ( event.clientX - windowHalfX ) / 2;
            mouseY = ( event.clientY - windowHalfY ) / 2;
        }
        //
        function animate() {
            requestAnimationFrame( animate );
            render();
        }


        function render() {
            //camera.position.x += ( mouseX - camera.position.x ) * .005;
            //camera.position.y += ( - mouseY - camera.position.y ) * .005;
            camera.lookAt( scene.position );
            renderer.render( scene, camera );
        }

If anyone can assist, I would greatly appreciate it! This is my first experience working with three.js.

Answer №1

I've successfully implemented the loader with the most recent version of ThreeJS. It seems like you're using version 73, but it's recommended to upgrade to v75 for better performance:

Check out this CodePen example

Download ThreeJS v75 here

Unfortunately, your server is blocking access to the object files, causing a CORS error. Loading them from the same domain should resolve this issue.

Without proper CORS headers allowing origin access, integrating these files into CodePen won't be possible.

> XMLHttpRequest cannot load
> http://hafsadanguir.com/THREEJS/obj/Heart.obj. No
> 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'http://s.codepen.io' is therefore not allowed
> access.

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

I am in search of a way to implement horizontal scrolling in Bootstrap 4

I am trying to implement a horizontal scroll feature in Bootstrap 4 with the following code, but I'm having difficulty achieving it. <div class="scroll-horz"> <div class="row"> <div class="col-md-4"> Test </div> < ...

Ways to block WebSocket access on a personal computer

Is it possible to protect my server resources from being accessed by other websites, such as example.com, via WebSocket? I want to prevent them from accessing the server using a URL like "ws://47.80.151.189:1234", and utilizing its resources (bandwidth, me ...

Understanding the method of recovering a nested promise

I am facing an issue with returning the result parameter from the getColumn function. Despite my attempts, it keeps logging as undefined. The connection function establishes a connection to a SQL database and retrieves a data set through a query. Is ther ...

Is it permissible for me to incorporate a package from the dependencies listed in the package-lock.json file into my

I'm looking to incorporate date-fns into my project. I currently have react-datepicker, which also uses date-fns. Can I simply utilize date-fns from react-datepicker, or do I need to install it separately in my project? ...

Utilizing Next 13 for flexible MDX imports

Recently completed the Next13 + MDX Tutorial, however, I am still unclear on how to dynamically load my mdx files. My mdx files are not hosted on a remote server, so I do not require next-mdx-remote. Nonetheless, I am in need of a method to load different ...

The URL remains unchanged even after clicking the search button using the post method

Whenever I visit a page with URL parameters, such as , and perform a search using the search button with form method = post, the URL maintains the previous parameter values even after displaying the search results. Even though it shows the search result, ...

aligning columns within a flexible element that has a maximum height

Within this flex element, I have set flex: column wrap; and max-height: 150px;. The issue I'm facing is that justify-content doesn't seem to be working. However, when I switch to using height: 150px, the alignment works fine. This problem arises ...

Challenges with Hover Dropdowns in Bootstrap Navigation Menu

Check out this screenshot of a navbar PSD design I'm aiming for: To make my navbar dropdown show up upon hovering, I've implemented the following JavaScript: $('.navbar .dropdown').hover(function() { $(this).find('.dropdown-men ...

Modifying arrays in ReactJS

Having trouble editing my array list, need some help. I can update a single input value successfully, but struggling with updating the entire array. Any suggestions on why the method isn't working and how to edit the array? When I try to store data ...

A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not. I am struggling with creating a function to move ...

Troubles with Express JS session handling

I've encountered a challenge with sessions in my Express app. After a successful login, the code should direct the user to the 'dashboard' page by default if no specific URL is requested. The login.js file sets req.session.user to a user i ...

Using an array of objects with useState

I have a search box where I can paste a column from Excel. Upon input, I parse the data and create an array of entries. Next, I loop through each entry and utilize a custom hook to retrieve information from my graphql endpoint. For instance: If 3 entrie ...

How can I retrieve the updated input value once a specific key has been pressed in the prototype?

After a customer presses any key, I would like to check an email. Below is the code I am using: document.observe("dom:loaded", function() { $('billing:email').observe('keypress', function(event){ console.log(event.element(). ...

Unable to modify text color after implementing mat-sort-header in Angular Datatable

My current setup involves using an Angular data table to display data. I recently added the mat-sort-header functionality, which allowed me to change the font color of the header text. Below is a breakdown of my code: <section id="main-content" ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...

Guide on utilizing substring string functions in the updated version of Selenium IDE

I am facing a challenge with extracting the word "Automation" from a given string "Welcome to the Automation World" using Selenium IDE Record and Play feature. I have tried using the execute script command, but it doesn't seem to be working as expecte ...

After successfully creating an account, the displayName consistently appears as null

I have a Vue project that utilizes Firebase as the backend. User registration is done using email and password. Below is the method used in Firebase: firebase.auth() .createUserWithEmailAndPassword(this.user.email, this.user.password) . ...

JavaScript and CSS animations offer dynamic and engaging ways to bring

I'm working on a div section and I want it to come down and rotate when a button is clicked. However, after moving to the bottom, it doesn't rotate as expected but instead returns to its initial position along the Y axis. How can I fix this issue ...

Using identical CSS styles across various classes in material UI

Three classes have been defined with identical CSS properties. const useStyles = makeStyles((theme) => ({ classA: { color: 'green' }, classB: { color: 'green' }, classC: { color: 'green' } }) Is there a way to combin ...

Arrange images in a fluid manner around other images

Check out the website I'm currently working on: metroweb.tk I'm in the process of designing a website that mimics the Windows 8 metro UI. However, I've encountered an issue with larger app icons such as notes and clocks sticking out. Is the ...