Modifying object dimensions in Three.js by adjusting the scale through the view

I am just starting with three.js and encountering an issue while trying to scale an object. I have already checked the documentation at https://github.com/mrdoob/three.js/wiki/Updates, but it's a bit overwhelming for me.

My problem is that when I change a HTML select element, the CubeGeometry should be scaled in the x-direction. It does scale correctly, but the previous cube remains, resulting in two cubes instead of one with the current size. I hope this makes sense!

Below is the snippet from my view:

$(document).on('change',".configurator > form select",function(event){

    // update 3D-object - not sure if this is the right way?
    $.getScript("/javascripts/3D-animation.js.erb", function(){
        // update happens here
        OBJECT3D.updateObject();
    });

})

And here is my 3D-animation.js.erb code:

var drawing_area;
var renderer;
var camera;
var obj;
var scene;

var OBJECT3D = {};

$(function() {

    // obtaining drawing area
    drawing_area = document.getElementById("canvas_wrapper");

    // initialize renderer
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(drawing_area.clientWidth, drawing_area.clientHeight);
    renderer.setClearColor( 0xffffff, 1);

    // adding renderer to drawing area
    drawing_area.appendChild(renderer.domElement);

    // initialize camera
    camera              = new THREE.PerspectiveCamera(45, drawing_area.clientWidth/drawing_area.clientHeight, 1, 100000);
    camera.position.z   = 1000;
    camera.position.y   = 100;
    camera.position.x   = 300;//-0.78;

    // creating texture
    var texture   = THREE.ImageUtils.loadTexture( "/images/materials/texture_1.jpg" );
    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;
    texture.repeat.set( 1, 1 );

    // creating object
    var obj_form        = new THREE.CubeGeometry(250,250,250);
    var obj_material    = new THREE.MeshLambertMaterial( { map: texture,ambient: 0x999999 } );
    OBJECT3D.obj        = new THREE.Mesh(obj_form, obj_material);

    OBJECT3D.obj.geometry.dynamic           = true;

    // create scene
    scene = new THREE.Scene();
    scene.add(camera);
    scene.add(OBJECT3D.obj);

    // create lights
    pointLight            = new THREE.PointLight(0xFFFFFF);
    pointLight.position.x = 400;
    pointLight.position.y = 200;
    pointLight.position.z = 1300;
    scene.add(pointLight);

    ambientLight = new THREE.AmbientLight( 0xffffff);
    scene.add( ambientLight );


    requestAnimationFrame(render);

    function render(){
        requestAnimationFrame(render);

        OBJECT3D.obj.rotation.y += 0.005; 
        OBJECT3D.obj.rotation.z += 0.005; 

        renderer.render(scene, camera);
    };

    OBJECT3D.updateObject = function () {
        console.log("in update");
        OBJECT3D.obj.scale.x = 2.5; // SCALE
        OBJECT3D.obj.geometry.needsUpdate = true;
    }

});

Apologies if the code is not perfect, as I am still learning! Thank you for your help!

Appreciate it!

Answer №1

It seems that the issue may be related to your use of the $.getScript method, which loads the script each time and creates a new instance of OBJECT3D.

To resolve this, I suggest ensuring that your code in 3D-animation.js.erb is included and called only once when the page loads (similar to other javascript files), and then calling the update function directly like so:

$(document).on('change',".configurator > form select", function(event) {
    OBJECT3D.updateObject();
});

Additionally, you can likely remove the following lines of code:

OBJECT3D.obj.geometry.needsUpdate = true;

and

OBJECT3D.obj.geometry.dynamic = true;

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

Display a secure background image using Angular 6

Even though I have successfully generated the image url to avoid any sanitizer errors, my background image is still not displaying. Is it necessary for me to utilize the "changingThisBreaksApplicationSecurity" property in order for the image to appear corr ...

The automatic message retrieval feature on the website for the PHP chat application is currently experiencing technical

When developing a PHP chat application, I have set status='0' for unread messages and status='1' for read messages as notifications. To enable auto-fetching of messages when a new message is received in the chat.php script, I have imple ...

JavaScript - Identifying Repetitive Items in an Array

My goal is difficult to explain in words, but I can show you with code. Here is the array I am working with: var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}] This array has duplicate elements, and I n ...

Differences in file loading in Node.js: comparing the use of .load versus command-line

Currently, I am in the process of developing a basic server using vanilla JavaScript and Node.js. For this purpose, I have created a file named database.js, which includes abstractions for database interactions (specifically with redis). One of my objecti ...

Swap out .h and .m files within an iOS project's bundle directory in real-time

I am currently using the calculation.h and calculation.m files for some calculations in my project. These calculations may need to be modified while the application is live on the store. Therefore, I can only make changes to these calculations and update t ...

unable to make a request to the express server with axios

I am in the process of developing a chat application similar to whatsapp. One of the key features I'm working on is that when a user clicks on another person's name, their chats will be displayed. However, currently, I'm facing an issue wher ...

Establish a connection with a particular endpoint using socket.io

I'm currently experimenting with socket.io, transitioning from the default JavaScript socket communication. Here's how I'm connecting in my current code: wsuri = "wss://" + window.location.hostname + ":9000"; sock = new WebSocket(wsuri); ...

Validating classes in Node.js using class-validator

I'm having some trouble with the class-validator package in my Node project. It's not being recognized and throwing an error. @MinLength(10, { ^ SyntaxError: Invalid or unexpected token Here's an example of what I'm doing: co ...

Submitting a file using Ajax XMLHttpRequest

Currently, I am facing an issue while attempting to send a file using the following XMLHttpRequest code. var url= "http://localhost:80/...."; $(document).ready(function(){ document.getElementById('upload').addEventListener('cha ...

Having issues with Bootstrap affix functionality malfunctioning

I recently put together documentation using the CSS and JavaScript from Bootstrap docs. Here is a snippet of the sidebar code in my documentation: <div class="col-md-3 docs"> <div class="bs-docs-sidebar"> <ul class="nav docs-sid ...

Expressing the relationship between API endpoints in a nested structure

I'm currently working on a REST API using expressjs. There are two api endpoints that I have defined: router.get('/probe/:id', function() {}); router.get('/:id', function() {}); However, I am facing an issue where calling the fir ...

Utilize Optional Chaining for verifying null or undefined values

I have utilized the following code: data?.response[0]?.Transaction[0]?.UID; In this scenario, the Transaction key is not present, resulting in the error message: ERROR TypeError: Cannot read properties of undefined (reading '0') Instead of chec ...

Exploring the AngularJS global Date timezone offset

I want to display dates based on the users' time zones. I am hoping that Angular provides a way to globally configure the Date filter for this purpose. Doing it manually for each case doesn't seem right to me. My timestamps are already passed t ...

Retrieving information from a JavaScript array outputs 'undefined'

I am currently attempting to retrieve the attribute labeled "MediaURL" from my Javascript array object. To provide a clearer understanding, the image below illustrates an expanded view of the array: https://i.sstatic.net/BWNym.png Encountering the follow ...

Navigating around potential type errors when passing data for chart.js can be challenging. Here are some strategies to

I'm currently working on an application that includes a chart, and I'm facing an issue while trying to populate the chart with data from my store. The error occurs when I attempt to pass the chartData object through props to the data property of ...

What to do when faced with an NPM issue: Resolving the error "Unable to assign properties to null (setting 'parent')"

The issue arises in NPM when working within a monorepo that utilizes the NPM workspaces feature. Within my monorepo, I have five packages: a, b, c, d, and e. Additionally, I have a package located in a separate repository that is not part of the workspace, ...

Creating an event declaration using Javascript's onclick function

As I was getting ready to add an onclick event to my element in JavaScript, a question popped into my mind regarding the efficiency of these two options: document.getElementById(myid).onclick = function(e){...} or document.body.onclick = fun ...

Display a confirmation dialog using AngularConfirm after a function in AngularJS has finished executing

Trying to figure out how to update the $ngConfirm box after a function is done. When submit is clicked, a spinning cog appears: https://i.sstatic.net/lxwrH.png $scope.inProgress = function(){ $ngConfirm({ theme: 'modern', i ...

What could be causing my AJAX form to refresh the page upon submission?

I have been working on a basic Follow/Unfollow system, and although the functionality is working correctly in terms of inserting and deleting rows when following/unfollowing, I'm facing an issue where the page refreshes every time despite using e.prev ...

Tips for updating the css class for multiple DOM elements using jQuery

I am currently attempting to modify the class property of a specific DOM element (in this case, a label tag) using jQuery version 1.10.2. Here is the code snippet I have written: var MyNameSpace = MyNameSpace || {}; MyNameSpace.enableDisableLabels = (f ...