Error message: Three JS is unable to locate the property 'add' due to its undefined status

Currently engaged in a project where a script fetches both a .svg and a .obj file upon clicking a button. The button successfully locates the files, but then encounters an error:

Uncaught TypeError: Cannot read property 'add' of undefined

Below is the code for the button. All other ThreeJS variables and calls are present in the HTML page and finish loading before the button is clicked.

function item(section, callback){
    var tmp = itemName.split('-');
    var cut = tmp[tmp.length-2];
    var styleNo = tmp[tmp.length-1];
    var path;
    var model;
    var loader = new THREE.OBJLoader( manager );
    if (_product.svgPathAbsolute) {
        path = itemName + '.svg';
        model = styleCode + '.obj';
    } else {
        path = _product[section].svgPath + _product.name.toLowerCase() + '/' + cut.toLowerCase() + '/' + itemName + '.svg';
        model = _product[section].svgPath + _product.name.toLowerCase() + '/' + cut.toLowerCase() + '/' + styleCode + '.obj';
    }

    loader.load( model, function ( object ) {
            object.traverse(function(node){
                if(node.material){
                    node.material.side = THREE.DoubleSide;
                    node.material = material;
                }
            });
            object.position.y = -100;
            geometry = object;
            scene.add(geometry);
        });

    $.get(path, function (svg) {
        _html[section] = svgToString(svg);
        callback(section);
    });
}

Included within the HTML

<script>
  var camera, scene, renderer, controls;
  var windowHalfX = window.innerWidth / 2;
  var windowHalfY = window.innerHeight / 2;
  var geometry;
  var material;
  var svg = document.getElementById("svg-holder").querySelector("svg");
  var img = document.createElement("img");
  var canvas = document.createElement("canvas");
  var svgSize = svg.getBoundingClientRect();
  canvas.width = svgSize.width;
  canvas.height = svgSize.height;
  var ctx = canvas.getContext("2d");
  var manager = new THREE.LoadingManager();
  manager.onProgress = function ( item, loaded, total ) {
    console.log( item, loaded, total );
  };
  var texture;

  var loader = new THREE.OBJLoader( manager );

  init();
  animate();
  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );
    camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
    camera.position.z = 150;
    // scene
    scene = new THREE.Scene();

    var ambientLight = new THREE.AmbientLight( 0xFFFFFF, 0.9 );
    scene.add( ambientLight );

    var directLight = new THREE.DirectionalLight( 0xFFFFFF, 0.2 );
    camera.add( directLight );
    scene.add( camera );

    controls = new THREE.OrbitControls( camera );
    controls.addEventListener( 'change', render );
    controls.minPolarAngle = 1.5;
    controls.maxPolarAngle = 1.5;

    var svgData = (new XMLSerializer()).serializeToString(svg);

    img.setAttribute("src", "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(svgData))) );
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
        var texture = new THREE.Texture(canvas);
        texture.needsUpdate = true;
        material = new THREE.MeshPhongMaterial({
        map: texture
        });
        material.map.minFilter = THREE.LinearFilter;
    };



    renderer = new THREE.WebGLRenderer({canvas:garmentOBJ,antialias:true});
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    //
    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 animate() {
    requestAnimationFrame( animate );
    render();
  }
  function render() {
    camera.lookAt( scene.position );
    renderer.render( scene, camera );
  }
</script>

Answer №1

Ensure that the scene object is accessible globally by either making it global or binding it to the window object, for example: window.scene = scene.

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

Guide on customizing the checkbox label class upon @change event in Vue?

Query: I have a list of checkboxes connected to an array of names. The objective is to alter the class of a specific name when its checkbox is clicked. Issue: Clicking on a checkbox causes all names to change class, instead of only affecting the one ass ...

Using PHP variables in JavaScript to access getElementById

I have multiple forms displayed on a single PHP page. They all follow a similar structure: <form id="test_form_1" action="test_submit.php" method="post" name="test_form"> <label>This is Question #1:</label> <p> &l ...

Cookie Session did not generate following a successful login

Hey there, I'm currently working on a MERN stack project where users can register and log in. However, I'm encountering an issue - even though the user successfully logs in, a session cookie is not being created. I've used the same logic in ...

Displaying and concealing a <div> within a list item

Although I know this question has been asked and answered numerous times, for some reason my code just won't cooperate. I'm attempting to make a div display on click inside an "li" element and remain hidden until clicked again, but the functional ...

Plane texture replication (WebGL, Three.JS)

I am currently utilizing three.js alongside webGL. In my project, I have a single texture file named support.jpg with dimensions 100x100. As part of the project, I am dynamically creating planes with varying heights and widths. My goal is to make the supp ...

Issue with burger menu functionality, button unresponsive

Two files are involved in this issue, one is a Vue file and the other is a JavaScript file. The JavaScript file contains an array and the problem is being described in the console. Additionally, there may be an issue with items as sometimes the same error ...

`Invoking a function from the parent of each child within the <view> array`

In React Native using JSX, I am working with a parent and child component setup. The parent component consists of an array of child components. There comes a point where I need to pause all child components by calling a specific method within each one of t ...

Angular JS Visibility Toggling with Ng-Show and Ng-Hide

Working on an angular service for a login form, I've successfully implemented authentication using a factory with an http injector to handle HTTP credentials. However, I'm facing an issue in displaying an error message when incorrect credentials ...

What is the best way to switch between my two images upon clicking?

When I click on an image, it changes to a different image. I achieved this by altering the source of the image upon clicking. Now, my goal is to incorporate a smooth transition between the two images after they are clicked. I attempted to stack the two im ...

The Algolia Hit Component is having difficulty functioning properly within a grid layout

I am in the process of converting my next API to an Algolia search. The Hit component is a single component that renders for each record. However, I am facing an issue with implementing a grid layout. Below is the code snippet from before (which was workin ...

Problem with validation in Asp.Net

One of the text boxes in my web form is configured to allow HTML tags to be submitted to the server. However, I have noticed that all HTML tags are working except for the meta tag. Do I need to make any configuration changes on the IIS side to enable this ...

Switching ng-show value from separate controller

I'm currently trying to update my ng-show variable whenever a state changes. In my default index.html file, the code looks like this: <div id="searchBar" ng-show="searchBar" ng-controller="mainController"></div> However, since this is no ...

Is there a way to execute the identical promise once more based on the outcome of the previous execution?

My dilemma involves a block of code enclosed within a promise. This particular code is responsible for modifying records in a remote database and reporting the number of records edited. In case the count of edited records exceeds 0 (indicating work done), ...

Building a Node.js authentication system for secure logins

Just diving into node.js and trying to create a user login system, but encountering an error when registering a new user: MongoDB Connected (node:12592) UnhandledPromiseRejectionWarning: TypeError: user is not a constructor at User.findOne.then.user ...

Unlocking the JSON array of data in JavaScript: A step-by-step guide

Hey there, I need help extracting an array from a JSON data structure. Here's an example of my JSON object: { Data1 : { Data2 : "hello", Data3 : "hi" }, Data4 : { Data5 : "this is Karan", } } I'm looking ...

Observing changes in VueJS using $watch and accessing DOM elements

How can I monitor changes in Vue $refs? I'm trying to apply some logic to a child component that is nested within my current Vue instance. However, when trying to access '$refs.childcomponent' inside the 'ready' callback, it appea ...

Responsive design involves ensuring that web elements such as divs are properly aligned

I am currently working on aligning 2 divs in a specific way that is responsive. I would like the right div to stack on top of the left div when the screen width reaches a certain point, as opposed to them both taking up 50% of the container's width. ...

The jquery selector fails to retrieve all elements

On the upcoming web page, I am attempting to use Jquery to select all <li> elements. Specifically, I want to target all the products contained within <ul class=search-result-gridview-items">. You can find the products here: I have made attempt ...

Meteor : Utilize a method on a specific data point

Currently, I am at the beginning stages of learning Meteor by following the official tutorial available at . My goal is to utilize the "createdAt" value stored in the database. Since this value is a Date object, my intention is to display the day of inser ...

Animating the thetaLength property of a RingBufferGeometry using GSAP and react-three-fiber

Is there a way to animate the ringBufferGeometry without using Math.sin() and instead utilizing GSAP for animation timing? I want the animation to stop when the thetaLength value reaches a certain point. Here is an example that showcases what I am trying t ...