Step-by-step guide on importing .obj and .mtl files into a Vue component with Vue CLI 3

Being new to VueJs and Three, my code is mostly just copied and pasted. I am trying to figure out how to load a 3D file (.obj) and its corresponding material file (.mtl) into a Vue component. I have already installed Three.js and imported the necessary loaders.

<template>
    <div id="container"></div>
</template>

<script>
import * as Three from 'three'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js'
export default {
  name: 'ThreeTest',
  data() {
    return {
      camera: null,
      scene: null,
      renderer: null,
      mesh: null,
      publicPath: 'process.env.BASE_URL',
      loader: null,
      loader2: null
     
    }
  },
  methods: {
    init: function() {
        let container = document.getElementById('container');
//camera
        this.camera = new Three.PerspectiveCamera(70, container.clientWidth/container.clientHeight, 0.01, 10);
        this.camera.position.z = 1;
//scene
        this.scene = new Three.Scene();
//obj loader
        this.loader = new OBJLoader();
        this.loader.load(`${this.publicPath}maquina1.obj`, (loadedObject) => {
        this.scene.add(loadedObject)
        console.log(loadedObject);})
//MTLLoader
        this.loader2 = new MTLLoader();
        this.loader2.load(`${this.publicPath}maquina1.mtl`, (loadedObject) => {
        this.scene.add(loadedObject)
        console.log(loadedObject);})
// Create and add AmbientLight.
//let light = new THREE.AmbientLight(0x404040); // soft white light
//this.scene.add(light);

//renderer
        this.renderer = new Three.WebGLRenderer({antialias: true});
        this.renderer.setSize(container.clientWidth, container.clientHeight);
        container.appendChild(this.renderer.domElement);
          },

    animate: function() {
        requestAnimationFrame(this.animate);
        this.renderer.render(this.scene, this.camera);
    }
  },
  mounted() {
      this.init();
      this.animate();
  }
}
</script>

<style scoped>
#container{
    width: 600px;
    height: 400px;
}
</style>

Currently, I am only seeing a black square and receiving the error "THREE.Object3D.add: object not an instance of THREE.Object3D." Also, it seems like the MTLLoader is not loading anything as the console displays an object with many values set to 0 or undefined.

Additionally, I am getting numerous warnings indicating that "THREE.OBJLoader: Unexpected line: "" as if OBJLoader is returning HTML content instead of a 3D image.

Answer №1

The issue arises from the fact that you have been loading files from the three/examples/js/ directory instead of loading all loaders from the three/examples/jsm/ directory. It seems you made this change for the DDSLoader but not for the other loaders.

For example:
Change:

import { OBJLoader } from 'three/examples/js/loaders/OBJLoader.js';
import { MTLLoader } from 'three/examples/js/loaders/MTLLoader.js'
import { DDSLoader } from 'three/examples/jsm/loaders/DDSLoader.js';

to

import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js'
import { DDSLoader } from 'three/examples/jsm/loaders/DDSLoader.js';

EDIT:
It seems you have modified the code in your original question, rendering the previous answer invalid.

You might not see anything on the screen because the renderer.render function is not being called anywhere in your code.

EDIT, Question changed again.
The line this.scene.add(x.this.scene ); is incorrect.
It should be this.scene.add(x);

Change:

new OBJLoader().load( 'ecoponto/public/maquina1.obj', function (x) {
  this.scene.add(x.this.scene );
}, undefined, function ( error ) {console.error( error );} );

to

let loader = new OBJLoader();
loader.load('ecoponto/public/maquina1.obj', (loadedObject) => {
  this.scene.add(loadedObject);
})

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

What is the best way to generate a responsive XML element in Vue 3?

In the realm of Vue 2, creating a reactive XML object was a breeze. With it, I could easily render a tree-like HTML view that depended on changes in the XML object to reflect the current state accurately. However, in the world of Vue 3, this functionality ...

Creating a dynamic 3x3 layout using flexbox: a step-by-step guide

Is it possible to dynamically create a layout in Next.js with 3 columns of 3 rows using flexbox, React Bootstrap, or CSS only? https://i.sstatic.net/tTinS.jpg ...

"Utilizing Bootstrap to ensure content is aligned perfectly to the baseline

I've been struggling to align my contents to the baseline while working with the bootstrap framework. I tried following the instructions in the documentation, but it didn't work out as expected. <div class="row"> <div class="col-12 ...

BS4 Dynamic Countdown Clock

I have successfully integrated a countdown timer into my website, utilizing the following HTML code: <div id="clockdiv"> <div> <span class="days"></span> <div class="smalltext">Days</ ...

Issue arising from CSS and div elements

I am facing some challenges in making certain divs behave as desired. Take a look at the following references: Link 1: - contains two divs Link 2: - has only one div I am trying to utilize two divs (.content) without them being positioned incorrectly ...

communicating between domains - js

Background: My latest project involves creating a web application that can download and display housing prices. The data source can be found at The Initial Plan: I aimed to fetch the data directly from the provided link using javascript, and then conver ...

Using Selenium and PhantomJS for web scraping to retrieve information on product details

As a beginner in web scraping with Python, I am currently working on extracting product details from a webpage using Selenium and PhantomJS. However, I am facing a challenge as the page does not display the rendered HTML when I try to access it using "driv ...

What is the best way to generate a dynamic div element filled with data?

When using inner HTML to dynamically retrieve divs with SQL Server data, I am encountering an issue where the div arrangement is not aligning horizontally. I need assistance in aligning them horizontally. Thank you. pnl_default.Visible = true; ...

Retrieve the value of a dynamically added or removed input field in JQuery using Javascript

Check out this informative article here I'm looking for a way to gather the values from all the text boxes and store them in an array within my JavaScript form. I attempted to enclose it in a form, but I'm struggling to retrieve the HTML ID beca ...

Tips for properly positioning items within the Bootstrap grid

I've been slowly working on developing the client side with Bootstrap, but I'm struggling to get the proportions of the authorization form right. I just want to align the logo and the authorization form on the same horizontal plane. Can someone p ...

Error: Definition Already Exists

I'm currently debugging a layout and encountering some peculiar errors. The page is being served as DTD XHTML 1.0 Strict. The error message looks like this: ID "OFFICENAME" already defined: div class="office" id="officename" ID "OFFICENAME" origin ...

Designing a Vue 3 JS component that showcases a collection of attributes for a movie catalog

I am aiming to utilize the movie_properties in order to store various details such as movie id, name, genre, comingSoon status, availability, thumbnail, and preview. It's important to note that I am working with an API call that contains all this inf ...

Tips on adjusting the rendering sequence of components in vueJs?

Is it possible to reorder child components based on data from an API in the parent component? Here is an example: Parent component: <div v-if="data"> <Component_1 /> <Component_2 /> <Component_3 /> <Com ...

When an element is dragged within the mcustomscrollbar container, the scroll does not automatically move downward

I am facing an issue where I have multiple draggable elements inside a Scrollbar using the mcustomscrollbar plugin. When I try to drag one of these elements to a droppable area located below the visible area of the scroller, the scroll does not automatical ...

Different option for positioning elements in CSS besides using the float

I am currently working on developing a new application that involves serializing the topbar and sidebar and surrounding them with a form tag, while displaying the sidebar and results side by side. My initial attempt involved using flex layout, but I have ...

The Laravel Posts that were made experienced a setback as the axios request failed to process with a status code

Encountering an issue with Laravel and Vue.js Every time I attempt to send a post request using axios, I am met with a server error 500. {Request failed with status code 500}. axios method: async callApi(method, url, dataObj ){ try { ...

choose and adjust elements within a three-dimensional scene using three.js

I have a JSON file containing object data that I load into my scene using ObjectLoader. After adding the objects to the scene, I want to customize their textures by adding parameters like THREE.SmoothShading and an envMap. I know how to find a specific obj ...

Utilize jQuery to send and load double values efficiently

When attempting to load the initial .load, I am able to pass 1 variable without any issues. I receive this variable from a _GET method, store it in a data-id button attribute, and pass it back to another .load. In the second file, I once again receive the ...

What strategies can be used to ensure that the page layout adjusts seamlessly to even the smallest shifts in window size?

Of course, I am familiar with media queries and how they allow us to set specific min-width and max-width ranges for CSS changes. However, when I look at the website styledotme.com, I notice that the block/div beneath the navigation bar gradually shrinks ...

Attaching dynamic data to a specific element within an array

I have successfully created a demo where elements can be dropped into a specific area and their top and left values are displayed. I have also added functionality to remove dropped items and move them between different blocks. However, I am encountering so ...