Resizing a cube in three.js

Here is my code using three.js:

cube = new THREE.Mesh(new THREE.CubeGeometry(200, 200, 200, 1, 1, 1, materials), new THREE.MeshFaceMaterial());
cube.position.y = 150;
cube.position.x = 0;
scene.add(cube);

However, I am facing an issue where the size of my cube keeps changing. To elaborate further, whenever I resize my browser and refresh the page, the cube's size differs each time. Is there a way to set a fixed size for the cube, regardless of window resizing?

Answer №1

To adjust the size of the renderer, you can set a fixed dimension:

renderer.setSize(WIDTH, HEIGHT);

Here is a straightforward example to illustrate this: http://jsfiddle.net/9stj8/

Be sure to verify if your code properly handles the window resize event.

Answer №2

Although this question has already received an answer, I wanted to contribute a little something for the sake of posterity and to ease the frustration levels of future readers.

In my experience with Three.js, I have primarily used the Perspective Camera over the orthographic camera. I recently came across a solution to the discussed problem related to setting up the perspective camera correctly:

  1. fov (vertical field of view angle)
  2. aspect ratio (width / height value) <-- Crucial!
  3. near clipping plane (object proximity threshold for visibility)
  4. far clipping plane (object distance threshold for invisibility)

The aspect ratio of the camera is essential for rendering properly in the viewport, especially when resizing the browser window. An inconsistency between viewport size and camera/renderer settings can result in distorted or incomplete images. To address this, you need to update the camera and renderer when the window size changes.

As suggested by Juan Mellado, you can adjust the viewport size using renderer.setSize(w,h). Here's how you can ensure that the camera and renderer adapt to window resize events:

function onResize()
        {
            var width, height;
            width = window.innerWidth; // for example
            height = window.innerHeight; // for example                

            //Update the camera's aspect ratio: width / height
            camera.aspect = width/height;

            //Don't forget to call updateProjectionMatrix() after making changes to the camera
            camera.updateProjectionMatrix();

            //Reset the renderer size to match the new dimensions
            renderer.setSize(width, height);
        }

To bind this callback function to the window.resize event, you can use either jQuery or plain JavaScript:

jQuery(window).resize(onResize);

or

window.onresize = onResize;

Summary:

1.) Make sure the values used to calculate Camera Aspect Ratio align with the renderer size values passed.

2.) Bind a callback function to the window.onresize event to ensure the camera aspect ratio and renderer size scale with the browser's dimensions.

3.) After modifying the camera post-creation, remember to invoke "updateProjectionMatrix()" to apply your changes.

If everything is set up correctly, the camera aspect ratio and renderer size will adjust automatically when resizing the window.

Happy coding!

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

Transmit information to Flask server using an AJAX POST call

I'm completely new to Ajax requests. I'm trying to send data from a webpage to my Flask backend using an Ajax request, but I can't get anything to show up in the backend: Here is the request code I am using: function confirm() { cons ...

Switch the class of the child element from the previous element using jQuery

I'm attempting to create a toggle effect on click that switches a class (font awesome) like this: $( ".expandTrigger" ).click(function() { $( ".expand" ).first().toggle( "fast", function() {}); if ( $( this ).prev().child().is( ".fa-plus-cir ...

Avoiding line breaks when submitting data through Ajax calls is achievable by using the `.val` method

I've come across multiple articles discussing ways to add line breaks to the .val in jQuery, but unfortunately none of them have worked for me. I attempted using the recommended workaround provided by jQuery: $.valHooks.textarea = { get: function( ...

"Excessive use of Javascript setInterval combined with frequent ajax calls is causing significant

I have integrated the setInterval() function into my JavaScript code to make an AJAX call every 2 minutes. However, I noticed that this is causing the website to slow down over time. The website is built using Node.js. After doing some research, I came acr ...

Fluidly insert or delete elements

Is there a way to retrieve deleted elements from the DOM after using the jquery .remove function? I have a scenario where I am removing elements from the DOM, but now I'm wondering if it's possible to bring back those deleted elements without hav ...

The voting system will increase or decrease by 1 to 5 during each round

Recently, I added a voting system to my website inspired by this source. It's functioning well, but there is an issue where each vote can sometimes count for more than one. You can view the source code on the original website and test it out live here ...

Chakra UI: How come the tooltip is appearing in the top left corner of the screen instead of directly above the element?

CreatedByModal is a unique chakra modal that incorporates tooltips. However, I am facing an issue where the tooltip appears at the top of the screen instead of directly above the icon when hovering over the icons. You can see in the image provided that the ...

Error: The file 'templates.js' cannot be found or accessed by gulp-angular-templatecache. Please check the file path and make sure it

I have set up a basic structure for creating angular templates using Gulp. Here is the code snippet from my gulpfile: var gulp = require("gulp"), templateCache = require('gulp-angular-templatecache'); gulp.task("tc", function() { retur ...

The initial attempt to use autocomplete with Jquery UI is not functioning as expected upon entry

I'm facing a frustrating issue that's driving me crazy. I'm not an expert in javascript, but I believe the solution is simple. I'm using jQuery UI autocomplete with data retrieved from Ajax. The problem is, I only get the desired resul ...

What is the process for closing the lightbox?

My code is supposed to display a lightbox as soon as the page loads, similar to a popup window. However, there seems to be an issue with closing the lightbox when clicking on the 'x' button at the corner of the box. Unfortunately, the current cod ...

Designing an interactive 3D space using JavaScript

I'm currently developing an app that allows users to visualize different wallpapers in a 3D room setting. The concept involves placing the user inside a virtual space with four walls, where they can drag and look around, as well as change wallpapers v ...

JavaScript and TypeScript: Best practice for maintaining an Error's origin

Coming from a Java developer background, I am relatively new to JavaScript/TypeScript. Is there a standard approach for handling and preserving the cause of an Error in JavaScript/TypeScript? I aim to obtain a comprehensive stack trace when wrapping an E ...

Is it possible to programmatically set focus on a DOM element using JavaScript or jQuery?

My code dynamically loads select boxes based on user selections. I have a specific instruction to select an option, which looks like this: //returns a string of <option>s by ID $('#subtopic_id').load('ajax.php?f=newSubtopic&am ...

Combining vueJS and webpack to bring in fonts, CSS styles, and node_modules into your project

I've recently started working with Vue.js and Webpack, and I'm facing some challenges regarding the correct way to import and reference fonts, CSS, and node_modules in my project. My project structure looks like this, as set up by vue-cli: buil ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Retrieve information from the existing URL and utilize it as a parameter in an ajax request

Currently, I am working on a website with only one HTML page. The main functionality involves fetching the URL to extract an ID and then sending it to an API using an AJAX call. Upon success, the data related to the extracted ID is displayed on the page. H ...

Align the position of two divs with matching IDs (#thumb-1 equals #project-1) using JavaScript or jQuery, but without the use of jQuery UI

I am currently working on creating a portfolio gallery and have put together the following HTML structure: <article class="work-gallery"> <ul> <li id="project-1"><img src="http://placehold.it/50x00"></li> ...

Tooltip remains visible even after formatting in highcharts

I have successfully hidden the datalabels with 0 values by formatting them. However, after formatting the tooltips for 0 valued data in a pie chart, there is an issue where hovering over the 0 valued portion shows a white box as shown in the picture. I hav ...

Publishing Your App on the Android Market with PhoneGap

Seeking a comprehensive PhoneGap tutorial that covers app publishing, especially struggling with successful app deployment. Currently experienced in HTML, CSS, and JavaScript. Any tips or advice would be greatly appreciated, thank you! I have a good gras ...

Concealing specific elements in Angular by utilizing ng-class conditions

Here's the code snippet I am currently working with: <tr ng-repeat="version in allVersions" ng-class="{{ version['active'] == 'true' ? 'active' : 'inactive' }}"> </tr> The ng-class is functioning ...